How are javascript arrays implemented?

后端 未结 9 767
天命终不由人
天命终不由人 2020-12-05 17:09

Namely, how does the following code:

var sup = new Array(5);
sup[0] = \'z3ero\';
sup[1] = \'o3ne\';
sup[4] = \'f3our\';
document.write(sup.length + \"
9条回答
  •  执笔经年
    2020-12-05 18:00

    This really depends on what you intend to do with it.

    [].length is "magical".
    It doesn't actually return the number of items in the array. It returns the largest instated index in the array.

    var testArr = [];  testArr[5000] = "something";  testArr.length; // 5000
    

    But the method behind the setter is hidden in the engine itself.
    Some engines in some browsers will give you access to their implementations of those magic-methods. Others will keep everything completely locked down.

    So don't rely on defineGetter and defineSetter methods, or even, really, __proto__ methods, unless you know which browsers you know you're targeting, and which you aren't.

    This will change in the future, where opt-in applications written in ECMAScript Next/6 will have access to more.

    ECMAScript 5-compliant browsers are already starting to offer get and set magic methods in objects and there's more to come... ...but it's probably a while away before you can dump support for oldIE and a tonne of smartphones, et cetera...

提交回复
热议问题