Rumah > hujung hadapan web > tutorial js > Kaedah statik objek - Cabaran JavaScript

Kaedah statik objek - Cabaran JavaScript

Susan Sarandon
Lepaskan: 2024-11-04 03:39:01
asal
531 orang telah melayarinya

Object static methods - JavaScript Challenges

Anda boleh menemui semua kod dalam siaran ini di repo Github.


Cabaran berkaitan kaedah statik objek


Object.assign()

/**
 * @param {any} target
 * @param {any[]} sources
 * @return {object}
 */
function myObjectAssign(target, ...sources) {
  if (target == null) {
    throw Error();
  }

  target = Object(target);

  function merge(keys = [], currSource) {
    for (const key of keys) {
      target[key] = currSource[key];

      if (target[key] !== currSource[key]) {
        throw Error();
      }
    }
  }

  for (const source of sources) {
    if (source == null) {
      continue;
    }

    merge(Object.keys(source), source);
    merge(Object.getOwnPropertySymbols(source), source);
  }

  return target;
}

// Usage example
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);

console.log(target); // => Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget === target); // => true
Salin selepas log masuk

Object.create()

/**
 * @param {any} proto
 * @return {object}
 */
function myObjectCreate(proto) {
  function MyConstructor() {}

  MyConstructor.prototype = proto.prototype ?? proto;

  return new MyConstructor();
}

// Usage example
const person = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  },
};
const me = myObjectCreate(person);
me.name = "Matthew"; // => "name" is a property set on "me", but not on "person"
me.isHuman = true; // Inherited properties can be overwritten
me.printIntroduction(); // => "My name is Matthew. Am I human? true"
Salin selepas log masuk

Object.groupBy()

/**
 * @param {Array} arr
 * @param {Function} iteratee
 * @return {Array}
 */

function groupBy(arr, iteratee) {
  const result = {};
  const iterateeFn =
    typeof iteratee === "function" ? iteratee : (value) => value[iteratee];

  for (const item of arr) {
    const key = iterateeFn(item);

    if (!Object.hasOwn(result, key)) {
      result[key] = [];
    }
    result[key].push(item);
  }

  return result;
}

// Usage example
console.log(groupBy([6.1, 4.2, 6.3], Math.floor)); // => { '4': [4.2], '6': [6.1, 6.3] }

// Group by string length
console.log(groupBy(["one", "two", "three"], "length"));
// => { '3': ['one', 'two'], '5': ['three'] }

const users = [
  { user: "barney", age: 36 },
  { user: "fred", age: 40 },
];

// Group by a property of the objects
console.log(groupBy(users, "age"));
// => { '36': [{'user': 'barney', 'age': 36}], '40': [{'user': 'fred', 'age': 40}] }
Salin selepas log masuk

Object.is()

/**
 * @param {any} op1
 * @param {any} op2
 * @return {boolean}
 */

function myObjectIs(op1, op2) {
  if (op1 === op2) {
    return a !== 0 || 1 / a === 1 / b;
  } else {
    return a !== a && b !== b;
  }
}

// Usage example
Object.is(+0, -0); // false
Object.is(NaN, NaN); // true
Salin selepas log masuk

Object.fromEntries()

/**
 * Creates an object from an array of key-value pairs.
 *
 * @param {Array} pairs - An array of key-value pairs.
 * @returns {Object} - The object composed from the key-value pairs.
 */

// One-line solution
function fromPairs(pairs) {
  return Object.fromEntries(pairs);
}

// Iterative solution
function fromPairs(pairs) {
  const result = {};

  for (const [key, value] of pairs) {
    result[key] = value;
  }

  return result;
}

// Usage example
const pairs = [
  ["a", 1],
  ["b", 2],
  ["c", 3],
];

console.log(fromPairs(pairs)); // => { a: 1, b: 2, c: 3 }
Salin selepas log masuk

Rujukan

  • GreatFrontEnd
  • 26. laksanakan Object.assign() - BFE.dev
  • 94. laksanakan Object.create anda sendiri - BFE.dev
  • 116. laksanakan Object.is() - BFE.dev
  • 177. Laksanakan Object.groupBy() - BFE.dev
  • Object.assign() - MDN
  • Object.create() - MDN
  • Object.fromEntries() - MDN
  • Object.groupBy() - MDN
  • Object.is() - MDN

Atas ialah kandungan terperinci Kaedah statik objek - Cabaran JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan