Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Array.prototype.with()

Baseline2023
Newly available

Thewith() method ofArray instances is thecopying version of using thebracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.

Syntax

js
arrayInstance.with(index, value)

Parameters

index

Zero-based index at which to change the array,converted to an integer.

  • Negative index counts back from the end of the array — if-array.length <= index < 0,index + array.length is used.
  • If the index after normalization is out of bounds, aRangeError is thrown.
value

Any value to be assigned to the given index.

Return value

A new array with the element atindex replaced withvalue.

Exceptions

RangeError

Thrown ifindex >= array.length orindex < -array.length.

Description

Thewith() method changes the value of a given index in the array, returning a new array with the element at the given index replaced with the given value. The original array is not modified. This allows you to chain array methods while doing manipulations.

By combiningwith() withat(), you can both write and read (respectively) an array using negative indices.

Thewith() method never produces asparse array. If the source array is sparse, the empty slots will be replaced withundefined in the new array.

Thewith() method isgeneric. It only expects thethis value to have alength property and integer-keyed properties.

Examples

Creating a new array with a single element changed

js
const arr = [1, 2, 3, 4, 5];console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]console.log(arr); // [1, 2, 3, 4, 5]

Chaining array methods

With thewith() method, you can update a single element in an array and then apply other array methods.

js
const arr = [1, 2, 3, 4, 5];console.log(arr.with(2, 6).map((x) => x ** 2)); // [1, 4, 36, 16, 25]

Using with() on sparse arrays

Thewith() method always creates a dense array.

js
const arr = [1, , 3, 4, , 6];console.log(arr.with(0, 2)); // [2, undefined, 3, 4, undefined, 6]

Calling with() on non-array objects

Thewith() method creates and returns a new array. It reads thelength property ofthis and then accesses each property whose key is a nonnegative integer less thanlength. As each property ofthis is accessed, the array element having an index equal to the key of the property is set to the value of the property. Finally, the array value atindex is set tovalue.

js
const arrayLike = {  length: 3,  unrelated: "foo",  0: 5,  2: 4,  3: 3, // ignored by with() since length is 3};console.log(Array.prototype.with.call(arrayLike, 0, 1));// [ 1, undefined, 4 ]

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-array.prototype.with

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp