js 对象会自动按键来进行排序的问题(自动排序)

问题描述

如以下示例:

const maps = {};
const l2 = [2,4,3,1];
const l1 = [5,6,4];
for (let index = 0; index < l2.length; index++) {
    if (l1[index] === undefined) {
        maps[l2[index]] = 0;
    } else {
        maps[l2[index]] =  l1[index];
    }
}
console.log(maps);
/// 输出结果 { '1': 0, '2': 5, '3': 4, '4': 6 }
/// 预期结果 { '2': 5, '4': 6, '3': 4, '1': 0}

原因分析:

确实是浏览器的关系。已查到V8的相关文档。Chrome会发生、FireFox不会。相关链接:
http://stackoverflow.com/questions/6166905/chrome-sorts-objects-by-key
http://code.google.com/p/v8/issues/detail?id=164


解决方案:

目前本人使用两种方式解决:

一. 使用Map对象,但有一个问题是键名不能重复:

const maps = new Map();
const l2 = [2, 4, 3, 1];
const l1 = [5, 6, 4];
for (let index = 0; index < l2.length; index++) {
    if (l1[index] === undefined) {
        maps.set(l2[index], 0);
    } else {
        maps.set(l2[index], l1[index]);
    }
}
/// 输出结果 Map { 2 => 5, 4 => 6, 3 => 4, 1 => 0 }
/// 预期结果 { '2': 5, '4': 6, '3': 4, '1': 0}
console.log(maps);

这种情况的问题:

/// 重复问题
const maps = new Map();
const l2 = [9,9,9,9,9,9,9];
const l1 =[9,9,9,9];
for (let index = 0; index < l2.length; index++) {
    if (l1[index] === undefined) {
        maps.set(l2[index], 0);
    } else {
        maps.set(l2[index], l1[index]);
    }
}
/// 输出结果 Map { 9 => 0 }
/// 预期结果 { '9': 9, '9': 9, '9': 9, '9': 9, '9': 0, '9': 0, '9': 0}
console.log(maps);

二、将键名加特殊标记字符

但注意,在使用时要去除掉特殊字符

const maps = {};
const l2 = [2,4,3,1];
const l1 = [5,6,4];
for (let index = 0; index < l2.length; index++) {
    if (l1[index] === undefined) {
        maps[`q${l2[index]}`] = 0;
    } else {
        maps[`q${l2[index]}`] =  l1[index];
    }
}

/// 输出结果 { q2: 5, q4: 6, q3: 4, q1: 0 }
/// 预期结果 { '2': 5, '4': 6, '3': 4, '1': 0}
console.log(maps);
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值