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

118 阅读1分钟

问题描述

如以下示例:

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不会。相关链接: stackoverflow.com/questions/6… code.google.com/p/v8/issues…


解决方案:

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

一. 使用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);