js常用寫法

moreas發表於2018-08-06

遍歷陣列 ES5 寫法

arr.forEach(function(value,index){
  console.log(index+`--`+value);
})

遍歷陣列  ES6 寫法

for( let i of arr){
  console.log(i);
}

判斷字串str是否以1開頭

str.indexOf(`1`) == 0

從集合中過濾符合條件的元素

var _ = require(`lodash`);
var users = [
    { `user`: `barney`, `age`: 36, `active`: true },
    { `user`: `fred`,   `age`: 40, `active`: false }
];
var rtnArr = _.filter(users, function(o) { return !o.active; });
console.log(rtnArr);
// [ { user: `fred`, age: 40, active: false } ]

判斷陣列中是否包含指定的字串

var fruits = ["Banana", "Orange", "Apple", "Mango"];
if(fruits.indexOf("Apple") > -1){
    console.log(`陣列中包含Apple`)
}else{
    console.log(`陣列中不包含Apple`)
}

 對陣列元素排序並拼接成字串

var arr = ["morris","20180823085422","715413099"];
var value = arr.sort();var value = value.join("");
console.log(value);

 

相關文章