Is it an antipattern to set an array length in JavaScript?

前端 未结 7 861
广开言路
广开言路 2020-12-08 13:18

Is it bad to use code like:

var a = [1,2,3,4];
a.length = 2; // 3 and 4 are removed

Does it have decent browser support? Do the removed val

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 13:50

    It's better to use slice because your intentions are clear.

    var truncated = a.slice(0,2)
    

    Slice does create a new array though.

    If that is an issue for you then there is nothing wrong with modifying the length property.

    It's actually the fastest way of truncation and supported in all browsers. jsperf

提交回复
热议问题