80 lines
2.1 KiB
JavaScript
80 lines
2.1 KiB
JavaScript
array = ["Bilbo", "Gandalf", "Nazgul"];
|
|
array.forEach((item, index, array) =>{
|
|
console.log(`${item} is at index ${index} in ${array}`)
|
|
});
|
|
|
|
console.log(`arr.indexOf(Bilbo): ${array.indexOf("Bilbo")}`)
|
|
console.log(`arr.indexOf(Bilbo): ${array.includes("Bilbo")}`)
|
|
|
|
let fruits = ['Apple', 'Orange', 'Apple']
|
|
console.log(`fruits.indexOf('Apple'): ${fruits.indexOf('Apple')}`)
|
|
console.log(`fruits.lastIndexOf('Apple'): ${fruits.lastIndexOf('Apple')}`)
|
|
|
|
// arr.find(fn)
|
|
let users = [
|
|
{id: 1, name: "xingzhesun"},
|
|
{id: 2, name: "zhexingsun"},
|
|
{id: 3, name: "sunxingzhe"},
|
|
];
|
|
|
|
let user1 = users.find(item => item.id == 1);
|
|
let user2 = users.findLastIndex(item => item.id == 1);
|
|
console.log(user1.name);
|
|
console.log(user2.name);
|
|
|
|
// arr.filter
|
|
let someUsers = users.filter(user => user.id < 3);
|
|
console.log(someUsers)
|
|
someUsers = users.filter(function(item, index, array){
|
|
if (item.id < 3){
|
|
return true;
|
|
}
|
|
})
|
|
console.log(someUsers);
|
|
|
|
// arr.map(fn)
|
|
let lengths = array.map(item=>item.length);
|
|
console.log(lengths);
|
|
|
|
// arr.sort(fn)
|
|
function compare(a, b){
|
|
if (a > b) return 1;
|
|
if (a == b) return 0;
|
|
if (a < b) return -1;
|
|
}
|
|
|
|
arr = [15, 2 ,1];
|
|
console.log(`arr.sort(): ${arr.sort(compare)}`);
|
|
console.log(`arr.sort(): ${arr.sort((a,b) => a - b)}`);
|
|
|
|
let countries = ['Österreich', 'Andorra', 'Vietnam'];
|
|
console.log(countries.sort((a,b) => a.localeCompare(b)))
|
|
|
|
// arr.reverse()
|
|
countries = countries.reverse()
|
|
console.log(countries)
|
|
|
|
// arr.split() and arr.join()
|
|
let names = "Bilbo, Gandalf, Nazgul";
|
|
|
|
let nameLists = names.split(', ');
|
|
|
|
for(let name of nameLists){
|
|
console.log(`A message to ${name}`);
|
|
}
|
|
// [LOG - 6/16/24 21:32:14] "A message to Bilbo"
|
|
// [LOG - 6/16/24 21:32:14] "A message to Gandalf"
|
|
// [LOG - 6/16/24 21:32:14] "A message to Nazgul"
|
|
|
|
nameLists = names.split(', ', 2);
|
|
for(let name of nameLists){
|
|
console.log(`A message to ${name}`);
|
|
}
|
|
// [LOG - 6/16/24 21:32:14] "A message to Bilbo"
|
|
// [LOG - 6/16/24 21:32:14] "A message to Gandalf"
|
|
|
|
console.log(`nameLists: ${nameLists.join('; ')}`)
|
|
// [LOG - 6/16/24 21:33:45] "nameLists: Bilbo; Gandalf"
|
|
|
|
|