javascript 新阵列方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 新阵列方法相关的知识,希望对你有一定的参考价值。

const princesses = [
  { name: "Rapunzel", age: 18 },
  { name: "Mulan", age: 16 },
  { name: "Anna", age: 18 },
  { name: "Moana", age: 16 }
];

// log the name of each princess, follow by a colon, followed by their age
// forEach: executes a provided function once for each array element
princesses.forEach(function(princess) {
  console.log(`${princess.name}: ${princess.age}`);
});

// create an array of just the names from the princesses array
// map: creates a new array with the results of calling a provided function on every element in the calling array
const names = princesses.map(function(princess) {
  return princess.name;
});
console.log("names: ", names);

// using the `names` array, get only those names that start with an 'M'
// filter: creates a new array with elements that pass the test of the provided function
const mNames = names.filter(function(name) {
  return name.startsWith("M");
});
console.log("m-names: ", mNames);

// get a single value from the data: the average age of all of the princesses
// reduce: applies a function against an "accumulator" and each element in the array (from left to right) to reduce it to a single value.
const sum = princesses.reduce(function(sum, princess) {
  return sum + princess.age;
}, 0);
const average = sum / princesses.length;
console.log("average age: ", average);

// BONUS: get the average age of all princesses whose name includes an 'l'
const lNames = princesses.filter(function(princess) {
  return princess.name.includes("l");
});

const lSum = lNames.reduce(function(sum, princess) {
  return sum + princess.age;
}, 0);

const lAverage = lSum / lNames.length;

console.log("l-average: ", lAverage);

以上是关于javascript 新阵列方法的主要内容,如果未能解决你的问题,请参考以下文章

javascript 常用阵列方法

Vue 旧阵列镜像新阵列

text Javascript ES6阵列图

javascript Uniq阵列

javascript 展平阵列

javascript [js- [阵列的API]]