Using the push method or .length when adding to array?

后端 未结 6 1824
慢半拍i
慢半拍i 2020-12-31 08:26

What are the downsides to doing:

var myArray = [];
myArray[myArray.length] = val1;
myArray[myArray.length] = val2;

instead of:



        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 08:56

    There seems to be discrepancy on which test is faster among the varying JavaScript engines. The differences in speed may be negligible (unless an unholy amount of pushes are needed). In that case, the prudent developer should always err on the side of readability. In this case, in my opinion and the opinion of @TheifMaster is that [].push() is cleaner and it is easier to read. Maintenance of code is the most expensive part of coding.

提交回复
热议问题