首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

array.unshift

unshift()方法将一个或多个元素添加到数组的开头,并返回新数组的长度。

var a = [1, 2, 3];
a.unshift(4, 5);

console.log(a); // [4, 5, 1, 2, 3]

语法

arr.unshift([element1[, ...[, elementN]]])

参数

element_N_要添加到数组开头的元素。

返回值

当一个对象调用该方法时,返回其length属性值。

描述

unshift方法会在调用它的类数组(array-like)对象的开始位置插入给定的参数。

unshift特意被设计成具有通用性;这个方法能够通过 callapply 方法作用于类似数组的对象上。不过对于没有 length 属性(代表从0开始的一系列连续的数字属性的最后一个)的对象,调用该方法可能没有任何意义。

示例

var arr = [1, 2];

arr.unshift(0); // result of call is 3, the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // = 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-3]);
// arr is [[-3], -2, -1, 0, 1, 2]

规范

Specification

Status

Comment

ECMAScript 3rd Edition (ECMA-262)

Standard

Initial definition. Implemented in JavaScript 1.2.

ECMAScript 5.1 (ECMA-262)The definition of 'Array.prototype.unshift' in that specification.

Standard

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Array.prototype.unshift' in that specification.

Standard

ECMAScript Latest Draft (ECMA-262)The definition of 'Array.prototype.unshift' in that specification.

Living Standard

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

1

(Yes)

1

5.5

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

1

(Yes)

(Yes)

(Yes)

扫码关注腾讯云开发者

领取腾讯云代金券