Why does Array.prototype.push return the new length instead of something more useful?

后端 未结 4 1851
悲哀的现实
悲哀的现实 2020-12-15 19:49

Ever since its introduction in ECMA-262, 3rd Edition, the Array.prototype.push method\'s return value is a Number:

4条回答
  •  醉梦人生
    2020-12-15 20:04

    I was curious since you asked. I made a sample array and inspected it in Chrome.

    var arr = [];
    arr.push(1);
    arr.push(2);
    arr.push(3);
    console.log(arr);
    

    Since I already have reference to the array as well as every object I push into it, there's only one other property that could be useful... length. By returning this one additional value of the Array data structure, I now have access to all the relevant information. It seems like the best design choice. That, or return nothing at all if you want to argue for the sake of saving 1 single machine instruction.

    Why was it done like this, and is there a historical record of how these decisions came to be made?

    No clue - I'm not certain a record of rationale along these lines exists. It would be up to the implementer and is likely commented in any given code base implementing the ECMA script standards.

提交回复
热议问题