Heim Web-Frontend js-Tutorial Array-Prototyp – JavaScript-Herausforderungen

Array-Prototyp – JavaScript-Herausforderungen

Nov 02, 2024 pm 08:05 PM

Array prototype - JavaScript Challenges

Sie finden den gesamten Code in diesem Beitrag im Repo Github.


Herausforderungen im Zusammenhang mit Array-Prototypen


Array.prototype.at()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

/**

 * @param {number} index

 * @return {any | undefiend}

 */

 

Array.prototype.myAt = function (index) {

  const len = this.length;

 

  if (index < -len || index >= len) {

    return;

  }

 

  return this[(index + len) % len];

};

 

// Usage example

console.log([1, 2, 3, 4].myAt(2)); // => 3

console.log([1, 2, 3, 4].myAt(-1)); // => 4

console.log([1, 2, 3, 4].myAt(5)); // => undefined

Nach dem Login kopieren

Array.prototype.concat()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

/**

 * @template T

 * @param {...(T | Array<T>)} itemes

 * @return {Array<T>}

 */

 

Array.prototype.myConcat = function (...items) {

  const newArray = [...this];

 

  for (const item of items) {

    if (Array.isArray(item)) {

      newArray.push(...item);

    } else {

      newArray.push(item);

    }

  }

 

  return newArray;

};

 

// Usage example

console.log([1, 2, 3].myConcat([])); // => [1, 2, 3];

console.log([1, 2, 3].myConcat([4, 5, 6, [2]])); // => [1, 2, 3, 4, 5, 6, [2]];

Nach dem Login kopieren

Array.prototype.every()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

/**

 * @template T

 * @param { (value: T, index: number, array: Array<T>) => boolean } callbackFn

 * @param {any} [thisArg]

 * @return {boolean}

 */

 

Array.prototype.myEvery = function (callbackFn, thisArg) {

  const len = this.length;

  let flag = true;

 

  for (let i = 0; i < len; i += 1) {

    if (Object.hasOwn(this, i) && !callbackFn.call(thisArg, this[i], i, this)) {

      flag = false;

      break;

    }

  }

 

  return flag;

};

 

// Usage example

console.log([1, 2, 3].myEvery((item) => item > 2)); // => false

console.log([1, 2, 3].myEvery((item) => item > 0)); // => true

Nach dem Login kopieren

Array.prototype.filter()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

/**

 * @template T, U

 * @param { (value: T, index: number, array: Array<T>) => boolean } callbackFn

 * @param { any } [thisArg]

 * @return {Array<T>}

 */

 

Array.prototype.myFilter = function (callbackFn, thisArg) {

  const newArray = [];

 

  for (let i = 0; i < this.length; i += 1) {

    if (Object.hasOwn(this, i) && callbackFn.call(thisArg, this[i], i, this)) {

      newArray.push(this[i]);

    }

  }

 

  return newArray;

};

 

// Usage example

console.log([1, 2, 3, 4].myFilter((value) => value % 2 == 0)); // => [2, 4]

console.log([1, 2, 3, 4].myFilter((value) => value < 3)); // => [1, 2]

Nach dem Login kopieren

Array.prototype.flat()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

/**

 * @param { Array } arr

 * @param { number } depth

 * @returns { Array }

 */

 

function flatten(arr, depth = 1) {

  const newArray = [];

 

  for (let i = 0; i < arr.length; i += 1) {

    if (Array.isArray(arr[i]) && depth !== 0) {

      newArray.push(...flatten(arr[i], depth - 1));

    } else {

      newArray.push(arr[i]);

    }

  }

 

  return newArray;

}

 

// Usage example

const words = ["spray", "elite", "exuberant", "destruction", "present"];

 

const result = words.filter((word) => word.length > 6);

 

console.log(result); // => ["exuberant", "destruction", "present"]

Nach dem Login kopieren

Array.prototype.forEach()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

/**

 * @template T, U

 * @param { (value: T, index: number, array: Array<T>) => U } callbackFn

 * @param {any} [thisArg]

 * @return {Array<U>}

 */

 

Array.prototype.myForEach = function (callbackFn, thisArg) {

  if (this == null) {

    throw new TypeError("this is null or not defined");

  }

 

  if (typeof callbackFn !== "function") {

    throw new TypeError(callbackFn + " is not a function");

  }

 

  const O = Object(this);

  // Zero-fill Right Shift to ensure that the result if always non-negative.

  const len = O.length >>> 0;

 

  for (let i = 0; i < len; i += 1) {

    if (Object.hasOwn(O, i)) {

      callbackFn.call(thisArg, O[i], i, O);

    }

  }

};

 

// Usage example

console.log(

  [1, 2, 3].myForEach((el) => el * el),

  null

); // => [1, 4, 9];

Nach dem Login kopieren

Array.prototype.indexOf()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

/**

 * @param {any} searchElement

 * @param {number} fromIndex

 * @return {number}

 */

 

Array.prototype.myIndexOf = function (searchElement, fromIndex = 0) {

  const len = this.length;

 

  if (fromIndex < 0) {

    fromIndex = Math.max(0, fromIndex + this.length);

  }

 

  for (let i = fromIndex; i < len; i += 1) {

    if (this[i] === searchElement) {

      return i;

    }

  }

 

  return -1;

}

 

// Usage example

console.log([1, 2, 3, 4, 5].myIndexOf(3)); // => 2

console.log([1, 2, 3, 4, 5].myIndexOf(6)); // => -1

console.log([1, 2, 3, 4, 5].myIndexOf(1)); // => 0

console.log(['a', 'b', 'c'].myIndexOf('b')); // => 1

console.log([NaN].myIndexOf(NaN)); // => -1 (since NaN !== NaN)

Nach dem Login kopieren

Array.prototype.last()

1

2

3

4

5

6

7

8

9

10

11

12

/**

 * @return {null|boolean|number|string|Array|Object}

 */

 

Array.prototype.myLast = function () {

  return this.length ? this.at(-1) : -1;

};

 

// Usage example

console.log([].myLast()); // => -1;

console.log([1].myLast()); // => 1

console.log([1, 2].myLast()); // => 2

Nach dem Login kopieren

Array.prototype.map()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

/**

 * @template T, U

 * @param { (value: T, index: number, array: Array<T>) => U } callbackFn

 * @param {any} [thisArg]

 * @return {Array<U>}

 */

 

Array.prototype.myMap = function (callbackFn, thisArg) {

  const len = this.length;

  const newArray = Array.from({ length: len });

 

  for (let i = 0; i < len; i += 1) {

    if (Object.hasOwn(this, i)) {

      newArray[i] = callbackFn.call(thisArg, this[i], i, this);

    }

  }

 

  return newArray;

};

 

// Usage example

console.log([1, 2, 3, 4].myMap((i) => i)); // => [1, 2, 3, 4]

console.log([1, 2, 3, 4].myMap((i) => i * i)); // => [1, 4, 9, 16])

Nach dem Login kopieren

Array.prototype.reduce()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

/**

 * @template T, U

 * @param { (previousValue: U, currentValue: T, currentIndex: number, array: Array<T>) => U } callbackFn

 * @param {U} [initialValue]

 * @return {U}

 */

 

Array.prototype.myReduce = function (callbackFn, initialValue) {

  const hasInitialValue = initialValue !== undefined;

  const len = this.length;

 

  if (!hasInitialValue && !len) {

    throw new Error("Reduce of empty array with no initial value");

  }

 

  let accumulator = hasInitialValue ? initialValue : this[0];

  let startingIndex = hasInitialValue ? 0 : 1;

 

  for (let i = startingIndex; i < len; i += 1) {

    if (Object.hasOwn(this, i)) {

      accumulator = callbackFn(accumulator, this[i], i, this);

    }

  }

 

  return accumulator;

};

 

// Usage example

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.myReduce((acc, num) => acc + num, 0);

console.log(sum); // => 15

const products = numbers.myReduce((acc, num) => acc * num, 1);

Nach dem Login kopieren

Array.prototype.some()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

/**

 * @template T

 * @param { (value: T, index: number, array: Array<T>) => boolean } callbackFn

 * @param {any} [thisArg]

 * @return {boolean}

 */

 

Array.prototype.mySome = function (callbackFn, thisArg) {

  const len = this.length;

  let flag = false;

 

  for (let i = 0; i < len; i += 1) {

    if (Object.hasOwn(this, i) && callbackFn.call(thisArg, this[i], i, this)) {

      flag = true;

      break;

    }

  }

 

  return flag;

};

 

// Usage example

console.log([1, 2, 3].mySome((item) => item > 2)); // => true

console.log([1, 2, 3].mySome((item) => item < 0)); // => false

Nach dem Login kopieren

Array.prototype.square()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

/**

 * @return {Array<number>}

 */

 

Array.prototype.mySquare = function () {

  const len = this.length;

  const newArray = Array.from({ length: len });

 

  for (let i = 0; i < len; i += 1) {

    newArray[i] = this[i] * this[i];

  }

 

  return newArray;

};

 

// Usage example

console.log([1, 2, 3].mySquare()); // => [1, 4, 9];

console.log([].mySquare()); // => [];

Nach dem Login kopieren

Referenz

  • GreatFrontEnd
  • Array.prototype.at() - MDN
  • Array.prototype.concat() – MDN
  • Array.prototype.every() – MDN
  • Array.prototype.filter() – MDN
  • Array.prototype.flat() – MDN
  • Array.prototype.forEach() – MDN
  • Array.prototype.indexOf() - MDN
  • Array.prototype.map() – MDN
  • Array.prototype.reduce() – MDN
  • Array.prototype.some() – MDN
  • 2635. Wenden Sie die Transformation auf jedes Element im Array an – LeetCode
  • 2634. Elemente aus Array filtern – LeetCode
  • 2626. Transformation zur Array-Reduzierung – LeetCode
  • 2619. Array-Prototyp zuletzt – LeetCode
  • 2625. Tief verschachteltes Array reduzieren – LeetCode
  • 3. Implementieren Sie Array.prototype.flat() - BFE.dev
  • 151. Implementieren Sie Array.prototype.map() - BFE.dev
  • 146. Implementieren Sie Array.prototype.reduce() - BFE.dev

Das obige ist der detaillierte Inhalt vonArray-Prototyp – JavaScript-Herausforderungen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße Artikel -Tags

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Ersetzen Sie Stringzeichen in JavaScript Ersetzen Sie Stringzeichen in JavaScript Mar 11, 2025 am 12:07 AM

Ersetzen Sie Stringzeichen in JavaScript

JQuery überprüfen, ob das Datum gültig ist JQuery überprüfen, ob das Datum gültig ist Mar 01, 2025 am 08:51 AM

JQuery überprüfen, ob das Datum gültig ist

JQuery Get Element Polsterung/Rand JQuery Get Element Polsterung/Rand Mar 01, 2025 am 08:53 AM

JQuery Get Element Polsterung/Rand

Top 5 Datum Manipulation JS -Plugins Top 5 Datum Manipulation JS -Plugins Feb 28, 2025 am 12:34 AM

Top 5 Datum Manipulation JS -Plugins

10 JQuery Accords Registerkarten 10 JQuery Accords Registerkarten Mar 01, 2025 am 01:34 AM

10 JQuery Accords Registerkarten

10 lohnt 10 lohnt Mar 01, 2025 am 01:29 AM

10 lohnt

JQuery fügen Sie Scrollbar zu Div hinzu JQuery fügen Sie Scrollbar zu Div hinzu Mar 01, 2025 am 01:30 AM

JQuery fügen Sie Scrollbar zu Div hinzu

HTTP-Debugging mit Knoten und HTTP-Konsole HTTP-Debugging mit Knoten und HTTP-Konsole Mar 01, 2025 am 01:37 AM

HTTP-Debugging mit Knoten und HTTP-Konsole

See all articles