以下函数运行有个奇怪的现象, list 结果[{ c: '--2' }, { c: '--2' }];
解决办法:
- list定义在循环内部则会按我所想的出现[{ c: '--1' }, { c: '--2' }];
- push时 arr.push(JSON.parse(JSON.stringify(list))) 对象复制一下
问题1:具体就是第二次循环时, push 内部arr为[{ c: '--2' }]?????
唯一的可能就是第一次push时已经循环完成,push进去的是 { c: '--2' }。
问题2:至于为啥push(k.c) 结果又是['--1','--2'] 呢, 而不是 ['--2', '--2']
拦截push方法,push k时 第一次就是{ c: '--2' }, push k.c 时,第一次是 '--1'
let arr = [];
const arr1 = [];
Array.prototype.push = function(...items) {
console.log('push---: ', items)
const O = Object(this);
const argCount = items.length >>> 0;
const len = O.length >>> 0;
if(argCount + len > 2*53 - 1)
throw new Error('数组长度已超出最大长度!')
let k =0;
for(; k<argCount; k++){
O[len + k] = items[k];
}
let newlen = argCount + len;
O.legnth = newlen;
return newlen;
}
function push(list){
// debugger
const doto = JSON.parse(JSON.stringify(list));
console.log('==pushed==', doto, arr);
console.log(Date.now());
arr.push(list.c)//当push(list)的时候结果为 --2
console.log(arr.map(item => item), arr);
function ppp(){
setTimeout(() => {
console.log('timeout: ', arr.shift());
},20000)
}
ppp()
}
const list = {};
[1,2].forEach(item => {
list.c = '--'+item;
console.log('for: ', list, Date.now());
push(list)
arr1.push(list)
console.log('----arr1---: ', JSON.parse(JSON.stringify(arr1)));
})
console.log('外部数组: ', arr1);
作为前端开发,这个问题是基于for循环产生mqtt发布数组发现的,后面没想明白,望各位大神指点,谢谢~~~
在js中,对象是引用型数据,第一次push的时候,他确实是1,但是第二次你改变了他的值,然后又push了它,此时数组中两个元素都是他,一模一样的它,而他的值是被你改过的
那为什么list.c结果就正常了呢,因为list.c不是引用型数据,是基本数据