【不断更新】JavaScript 各种 demo

---------------------------------------------- 尊重原创,转载请注明出处。----------------------------------------------

1.数组去重

let arr = [1, 3, 3, 5];

// 方法1
// Array.from(): 将其他对象转化为数组
// set数据结构:ES6,类似于数组,但其成员值都是唯一的

let method1 = array => Array.from(new Set(array));
console.log(method1(arr)); // [1,3,5]

// 方法2(类似方法1)
const method2= arr => [...new Set(arr)];
console.log(method2(arr)); // [1,3,5]

// 方法3
let method3 = array => {
    let newArr = [];
    for(let i = 0; i < array.length; i++){
        if(!newArr.includes(array[i])){
            newArr.push(array[i]);
        }
    }
    return newArr;
}
console.log(method3(arr)); // [1,3,5]

2.多种语言打印 Hello, world!

console.log('Hello, world!');             // JavaScript
std::cout<<"Hello, world!"<<std::endl;    // C++
System.out.printIn("Hello, world!");      // Java
printf("Hello, world!");                  // C
Console.WriteLine("Hello, world!");       // C#
print "Hello, world!";                    // python
echo "Hello, world!";                     // php

3.取得数组中最大和最小值

let arr = [2, 3, 6, 1, 3];

// 方法1
// 依次比较
let max = min = arr[0];
for(let i = 0; i < arr.length; i++){
    max < arr[i] ? max = arr[i] : null;
    min > arr[i] ? min = arr[i] : null;
}
console.log(`max: ${max}, min: ${min}`);

// 方法2
// 对数组排序(小 > 大),第一个是最小值,最后一个是最大值
arr.sort((a,b) => a-b);
let min = arr[0];
let max = arr[arr.length-1];

// 方法3
// Math.max(a,b..) 方法返回参数中较大的值
let max = Math.max.apply(null, arr);
let min = Math.min.apply(null, arr);
// ES6的写法
let max = Math.max(...arr);
let min = Math.min(...arr);

// 多维数组,则先转化为一维数组
// join方法:将数组里所有元素放入一个字符串
// split方法:把一个字符串分割为字符串数组
let newArr = arr.join(',').split(',');

4.数组排序

let arr = [3, 1, 7, 5, 9];

// 方法1
// sort方法会改变数组本身
arr.sort((a,b) => a-b); // 从小到大
console.log(`从小到大:${arr}`);
arr.sort((a,b) => b-a); // 从大到小
console.log(`从大到小:${arr}`);

5.颠倒数组

let arr = [1, 2, 3, 4, 5];

// 方法1
// reverse()方法会改变原数组,不会返回新数组
arr.reverse();
console.log(arr);

// 方法2 
// 前后交换
let val, len = arr.length;
for(let i = 0; i < len / 2; i++){
    val = arr[i];
    arr[i] = arr[len-i - 1];
    arr[len-i - 1] = val;
}
console.log(arr);

// 颠倒字符串
let str = 'hello';
let newStr = [...str].reverse().join('');
console.log(newStr);  // olleh

6.在canvas 上绘制一个圆和一个长方形(假设不重叠),且点击圆的时候控制台可以
输出Circle,点击长方形的时候控制台可以输出Rect。

 

7.合并数组

let arr1 = [1, 2, 3],
    arr2 = [4, 5, 6],
    arr3 = [7];

// m1
let aaa = arr1.push(...arr2, ...arr3);    // 放在 arr1的末尾, 并返回新的长度
console.log(aaa);  // 7
console.log(arr1); // [1, 2, 3, 4, 5, 6, 7]
// 放在开头则使用 unshift() 方法

// m2
for(let i of arr2){
    arr1.push(i);
}
for(let i of arr3){
    arr1.push(i);
}
console.log(arr1); // [1, 2, 3, 4, 5, 6, 7]

// m3 es5
let newArr = arr1.concat(arr2, arr3);
console.log(newArr);

// m4
let newArr = [...arr1, ...arr2, ...arr3];
console.log(newArr);

8.依次打印数组元素

// method1
for(let i = 0; i < arr.length; i++){
    console.log(arr[i]);
} 

// method2
// i is the value of arr
for(let i of arr){
    console.log(i);
}

// method3
// i is the index
for(let i in arr){
    console.log(arr[i]);
}

// method4
arr.forEach((value, index, arr) => {
    console.log(value);
});

// method5
let newArr = arr.map((val, index, arr) => {
    console.log(val);
    return val + 1;
});
console.log("map newArr +1: " + newArr);
// foreach 中 return 无效,map 中 return 会返回一个新的被改变后的数组
// map 中不用 return 的话,和 foreach 一样
// map 的目的是改变值,filter 的目的是筛去不需要的值

// method6
let newArr6 = arr.filter((val, i, arr) => {
    console.log(val);
    if(val === 2){
        return false;
    } else {
        return true;
    }
});
console.log("filter newArr delete 2: " + newArr6);

9.将字符串转化为数组,数组转化为字符串

let str = 'h,e,l,l,o';

// m1
let arr1 = [...str];
let arr2 = str.split('');
let arr3 = str.split(',');
let arr4 = Array.from(str);
console.log(arr1); // ["h", ",", "e", ",", "l", ",", "l", ",", "o"]
console.log(arr2); // ["h", ",", "e", ",", "l", ",", "l", ",", "o"]
console.log(arr3); // ["h", "e", "l", "l", "o"]
console.log(arr4); // ["h", ",", "e", ",", "l", ",", "l", ",", "o"]


let arr = ['h','e','l','l','o'];
let str1 = arr.join('');
console.log(str1); // hello

10.找出数组中所有小于0的数 

let arr = [2, 8, -5, 3, -9];

// m1
for(let i of arr){
    i < 0 ? console.log(i) : null;  // -5
                                    // -9
}

// m2
// find 方法只能找到第一个符合条件的值, 不存在就返回 undefined
// findIndex 返回第一个符合条件的值的 index,不存在就返回 -1

for(let i of arr){
    let num = arr.find((val) => val < 0);
    num === undefined ? null : console.log(num);
    let index = arr.findIndex((val) => val < 0);
    arr.splice(index, 1);
}

11.将一维数组转化为二维数组

let arr =  [0, 1, 2, 3, 4, 5]
let newArr = []; // [[0, 1], [2, 3], [4, 5]

function fn(arr, num){
    let newArr = [];
    for(let i = 0; i < arr.length/num; i++){
        for(let j = 0; j < arr.length; j++){
            if(i * num <= j < (i+1) * num){
                newArr[i].push(arr[i]);
            }
        }
    }
    return newArr;
}

12.判断一个变量是数组还是对象

            let arr = [1, 2, 3];
            let obj = {
                name: 'Turing',
            }
            function judgeVar(variable){
                // 方法1,instanceof 与 typeof 运算符相似,用于识别正在处理的对象的类型
                return typeof variable === 'object' &&  variable instanceof Array ? '数组' : '对象';
                // 方法2,constructor 属性返回对创建此对象的数组函数的引用
                return typeof variable === 'object' &&  variable.constructor === Array ? '数组' : '对象';
            }
            console.log(judgeVar(arr));  // 数组
            console.log(judgeVar(obj));  // 对象

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章