gpt4 book ai didi

javascript - (为什么)设置 `array[NaN]` 没有任何作用?

转载 作者:行者123 更新时间:2023-12-03 06:45:26 25 4
gpt4 key购买 nike

我正在阅读an article about javascript PRNGs ,我发现了一些令我惊讶的事情:

var a = new Array();
var b;
a[b++] = 1;

a is now [] and no exception is thrown — the write to the array simply vanishes. Try it out in your browser console if you don’t believe me.

我不相信他,所以我在浏览器控制台(Firefox 47)中尝试了一下:

» var a = new Array();
» var b;
» a[b++] = 1

» a
← Array [ ]
» b
← NaN

这里发生了一些奇怪的事情,但特别是,我试图理解为什么语句 a[b++] = 1 没有[似乎]做任何事情。

最佳答案

从顶部开始:

var a = new Array();
// 'a' is now an empty array, plain ol' boring empty array, could have been
// written as a = [];
var b;
// 'b' have no value and is 'undefined'. 'console.log(b); // undefined'
a[b++] = 1;
// Lets break the above statement down into pieces:
b++ // Increment b by one, undefined + 1 === NaN
a[ ] // Use NaN as a property for our array 'a'
= 1; // Assign 1 to that property
// Ok? So what happened why does 'a' still look empty?
console.log(a); // []
// The way your console with show you an array is by printing the numeric keys
// in it, and looking at the length, eg:
// var q = [];
// q.length = 1;
// console.log(q); // [undefined x 1]

// With 'a' in our case there is no numeric keys in it so [] is printed.
// So did our value dissapear?
// No. It is there:
console.log('NaN' in a); // true
// And:
for (var prop in a) console.log(prop); // NaN

// Why is this even a feature?
// Arrays are extending Objects so they have the same properties as em.
console.log(a instanceof Object); // true
console.log(a instanceof Array); // true

关于javascript - (为什么)设置 `array[NaN]` 没有任何作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37762832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com