iT邦幫忙

2

13個有用的JavaScript 陣列 小條目 (part1)

  • 分享至 

  • xImage
  •  

根據這篇 https://dev.to/duomly/13-useful-javascript-array-tips-and-tricks-you-should-know-2jfo

所做記錄

1.從陣列中刪除重複

var fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];


var uniqueFruits =Array.from(new Set(fruits));

console.log(uniqueFruits);

var uniqueFruits2 = [...new Set(fruits)];

2.不用 map() 的陣列

var friends = [
    { name: 'John', age: 22 },
    { name: 'Peter'’, age: 23 },
    { name: 'Mark', age: 24 },
    { name: 'Maria', age: 22 },
    { name: '‘Monica', age: 21 },
    { name: 'Martha', age: 19 },
]

var NewFriends = Array.from(friends, ({name})=> name)

console.log(NewFriends);
// returns [“John”, “Peter”, “Mark”, “Maria”, “Monica”, “Martha”]


3.清空 陣列

var fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];


fruits.length = 0;
console.log(fruits); // returns []

5.將陣列轉換為物件

var fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];

var obj ={...fruits};

console.log(obj);

6.快速陣列填充

var newArray = new Array(10).fill('1');
console.log(newArray);
return  ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]

7.合併陣列

var fruits = ['apple', 'banana', 'orange'];
var meat = ['poultry', 'beef', 'fish'];
var vegetables = ['potato', 'tomato', 'cucumber'];
var food = [...fruits, ...meat, ...vegetables];

console.log(food);
// [“apple”, “banana”, “orange”, “poultry”, “beef”, “fish”, “potato”, “tomato”, “cucumber”]

8.找出兩個陣列交集之處

使用 filter() 和 includes() 方法

var numOne = [0, 2, 4, 6, 8, 8];
var numTwo = [1, 2, 3, 4, 5, 6];


var newSet = [...new Set(numOne)].filter(item => numTwo.includes(item));
console.log(newSet);

9.隨機產生數組

var colors = ['blue', 'white', 'green', 'navy', 'pink', 'purple', 'orange', 'yellow', 'black', 'brown'];



var randomColor = colors[(Math.floor(Math.random() * (colors.length)))];
console.log(randomColor);

13.數值求和

var nums = [1, 5, 2, 6];
var sum = nums.reduce((x, y) => x + y);
console.log(sum); // returns 14

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言