当前位置: 首页 > news >正文

JavaScript 系列之:数组、树形结构等操作

数组

查找

find

查找第一个符合条件的元素,并返回该元素。

如果没有找到符合条件的元素,则返回 undefined。

array.find(callback(element[, index[, array]])[, thisArg])
  • callback:用于测试每个元素的函数,接收三个参数:

    • element:当前正在处理的数组元素。

    • index(可选):当前元素的索引。

    • array(可选):调用 find() 的原始数组。

  • thisArg(可选):执行 callback 时作为 this 的值。

示例:

const users = [{ id: 1, name: 'Alice' },{ id: 2, name: 'Bob' },{ id: 3, name: 'Charlie' }
];// 查找 id 为 2 的用户
const user = users.find(user => user.id === 2);console.log(user); // 输出: { id: 2, name: 'Bob' }

filter

条件过滤,返回新数组,如果没有符合条件的元素则返回空数组。

const newArray = array.filter(callback(element[, index[, array]])[, thisArg]);
  • callback:用于测试每个元素的函数,接收三个参数:

    • element:当前正在处理的数组元素。

    • index(可选):当前元素的索引。

    • array(可选):调用 filter() 的原始数组。

  • thisArg(可选):执行 callback 时作为 this 的值。

示例:

const people = [{ name: 'John', age: 25 },{ name: 'Jane', age: 17 },{ name: 'Mike', age: 30 },{ name: 'Sarah', age: 15 }
];const adults = people.filter(person => person.age >= 18);
console.log(adults);
// 输出: [{ name: 'John', age: 25 }, { name: 'Mike', age: 30 }]

some

用于检测数组中是否至少有一个元素满足指定的条件。如果有任何一个元素满足条件,some() 返回 true,否则返回 false。

一旦找到满足条件的元素就会立即停止遍历。

array.some(callback(element[, index[, array]])[, thisArg])
  • callback:必需的回调函数,用于测试每个元素,它可以接收三个参数:

    • element:当前正在处理的数组元素。

    • index(可选):当前元素的索引。

    • array(可选):调用 some() 的原始数组。

  • thisArg(可选):执行 callback 时作为 this 的值。

示例:

const users = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 30 },{ name: 'Charlie', age: 20 }
];const hasAdult = users.some(user => user.age >= 18);
console.log(hasAdult); // trueconst hasSenior = users.some(user => user.age >= 65);
console.log(hasSenior); // false

every

用于检测数组中的所有元素是否都满足指定的条件。如果所有元素都通过测试,则返回 true,否则返回 false。

一旦找到不满足条件的元素就会立即停止遍历。

array.every(callback(element[, index[, array]])[, thisArg])
  • callback:必需的回调函数,用于测试每个元素,它可以接收三个参数:

    • element:当前正在处理的数组元素。

    • index(可选):当前元素的索引。

    • array(可选):调用 every() 的原始数组。

  • thisArg(可选):执行 callback 时作为 this 的值。

示例:

const users = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 30 },{ name: 'Charlie', age: 20 }
];const test1 = users.every(user => user.age >= 18);
console.log(test1); // trueconst test2 = users.every(user => user.age >= 25);
console.log(test2); // false

findIndex

用于查找数组中第一个满足指定条件的元素的索引。如果找到匹配的元素,则返回该元素的索引;如果没有找到,则返回 -1。

array.findIndex(callback(element[, index[, array]])[, thisArg])
  • callback:必需的回调函数,用于测试每个元素,它可以接收三个参数:

    • element:当前正在处理的数组元素。

    • index(可选):当前元素的索引。

    • array(可选):调用 findIndex() 的原始数组。

  • thisArg(可选):执行 callback 时作为 this 的值。

示例:

const users = [{ name: "Alice", age: 25 },{ name: "Bob", age: 30 },{ name: "Charlie", age: 17 }
];// 查找第一个未成年人的索引(正确示例)
const firstMinorIndex = users.findIndex(user => user.age < 18);
console.log(firstMinorIndex); // 输出: 2(因为 Charlie 是未成年人,索引为 2)// 查找第一个年龄 >= 30 的用户的索引(修正后的示例)
const firstAdultIndex = users.findIndex(user => user.age >= 30);
console.log(firstAdultIndex); // 输出: 1(因为 Bob 的年龄是 30,索引为 1)

新增/删除

slice 截取

可用于数组和字符串,用于提取数组或字符串的一部分并返回一个新的数组或字符串。

特点:

  • 不会修改原数据

  • 返回新的数据

array.slice(startIndex, endIndex);
  • startIndex(可选):开始提取的索引(从 0 开始)。若为负数,则从数组末尾倒数(如 -1 表示最后一个元素)。

  • endIndex(可选):提取的结束索引(不包含该索引的元素)。若省略,则提取到数组末尾;若为负数,同样从末尾倒数。

示例:

const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];// 示例1: 提取从索引1开始到结束
const fruits1 = fruits.slice(1);
console.log(fruits1); // ['banana', 'orange', 'grape', 'kiwi']// 示例2: 提取从索引1到3(不包括3)
const fruits2 = fruits.slice(1, 3);
console.log(fruits2); // ['banana', 'orange']// 示例3: 使用负数索引
const fruits3 = fruits.slice(-3); // 从倒数第3个元素开始
console.log(fruits3); // ['orange', 'grape', 'kiwi']const fruits4 = fruits.slice(-4, -1);
console.log(fruits4); // ['banana', 'orange', 'grape']// 示例4: 复制整个数组
const fruitsCopy = fruits.slice();
console.log(fruitsCopy); // ['apple', 'banana', 'orange', 'grape', 'kiwi']fruitsCopy[0] = 'iphone' // 浅拷贝
console.log(fruitsCopy); // ['iphone', 'banana', 'orange', 'grape', 'kiwi']// 示例5: 原始数组未被修改
console.log(fruits); // ['apple', 'banana', 'orange', 'grape', 'kiwi']

splice 删除/添加/替换

可以实现删除、添加和替换数组元素的功能。splice() 会直接修改原始数组。

特点:

  • 会修改原数据

  • 若有元素被删除或替换,则返回被删除或替换的元素组成的数组

  • 若没有,则返回空数组 []

array.splice(start[, deleteCount[, item1[, item2[, ...]]])splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* …, */ itemN)
  • start:指定修改的开始位置(从 0 开始计数)

    • 如果为负数,表示从数组末尾开始的偏移量

    • 如果大于数组长度,则从数组末尾开始

    • 如果绝对值大于数组长度,则从 0 开始

  • deleteCount(可选):要删除的元素个数

    • 如果省略或大于从 start 到数组末尾的元素数量,则删除从 start 到数组末尾的所有元素

    • 如果为 0 或负数,则不删除元素

  • item1, item2, …(可选):要添加到数组的元素,从 start 位置开始插入

示例:

1、删除元素

const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];// 从索引2开始删除1个元素
const removed = fruits.splice(2, 1);
console.log(fruits);  // ['apple', 'banana', 'grape', 'kiwi']
console.log(removed); // ['orange']// 从索引1开始删除2个元素
const removed2 = fruits.splice(1, 2);
console.log(fruits);  // ['apple', 'kiwi']
console.log(removed2); // ['banana', 'grape']

2、添加元素

const colors = ['red', 'green', 'blue'];// 从索引1开始删除0个元素,添加'yellow'和'purple'
const add1 = colors.splice(1, 0, 'yellow', 'purple');
console.log(colors); // ['red', 'yellow', 'purple', 'green', 'blue']
console.log(add1) // []// 从末尾第二个位置开始添加
const add2 = colors.splice(-1, 0, 'white');
console.log(colors); // ['red', 'yellow', 'purple', 'green', 'white', 'blue']
console.log(add2) // []

3、替换元素

const numbers = [1, 2, 3, 4, 5];// 从索引1开始删除2个元素,并添加'a'和'b'
const replaced = numbers.splice(1, 2, 'a', 'b');
console.log(numbers);  // [1, 'a', 'b', 4, 5]
console.log(replaced); // [2, 3]// 替换最后一个元素
numbers.splice(-1, 1, 'last');
console.log(numbers); // [1, 'a', 'b', 4, 'last']

4、特殊情况

const arr = [1, 2, 3, 4, 5];// start大于数组长度
arr.splice(10, 1, 'a'); // 从末尾开始添加
console.log(arr); // [1, 2, 3, 4, 5, 'a']// start为负数且绝对值大于数组长度
arr.splice(-10, 2); // 相当于从索引0开始删除2个元素
console.log(arr); // [3, 4, 5, 'a']// deleteCount为0
arr.splice(1, 0, 'b', 'c'); // 只添加不删除
console.log(arr); // [3, 'b', 'c', 4, 5, 'a']

unshift 开头添加

unshift() 用于在数组的开头添加一个或多个元素,并返回新的数组长度。

特点:

  • 会修改原数据

  • 返回新的数组长度

array.unshift(element1, element2, ..., elementN);

示例:

const numbers = [3, 4];
numbers.unshift(1, 2);
console.log(numbers);     // 输出: [1, 2, 3, 4]const arr = [3, 4];
arr.unshift([1, 2]);
console.log(arr);         // 输出: [[1, 2], 3, 4]

push 结尾添加

push() 用于在数组的结尾添加一个或多个元素,并返回新的数组长度。

特点:

  • 会修改原数据

  • 返回新的数组长度

array.push(element1, element2, ..., elementN);

示例:

const numbers = [1, 2];
numbers.push(3, 4);
console.log(numbers);     // 输出: [1, 2, 3, 4]const arr = [1, 2];
arr.push([3, 4]);
console.log(arr);         // 输出: [1, 2, [3, 4]]

shift 删除第一个

shift() 删除并返回数组的第一个元素,同时将剩余元素的索引前移。与 pop() 方法(删除最后一个元素)相对应。

特点:

  • 会修改原数据

  • 返回数组被删除的第一个元素

const fruits = ['apple', 'banana', 'cherry'];
const removed = fruits.shift();console.log(removed);   // 输出: 'apple'
console.log(fruits);    // 输出: ['banana', 'cherry']

pop 删除最后一个

pop() 删除并返回数组的最后一个元素。

特点:

  • 会修改原数据

  • 返回数组被删除的最后一个元素

const fruits = ['apple', 'banana', 'cherry'];
const removed = fruits.pop();console.log(removed);   // 输出: 'cherry'
console.log(fruits);    // 输出: ['apple', 'banana']

其他

reduce 累加器

reduce() 会遍历数组,将前一次回调的结果作为下一次的累加器,最终返回单个值。

array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
  • callback:处理每个元素的函数,包含四个参数:

    • accumulator:累加器,存储上一次回调的返回值。

    • currentValue:当前处理的数组元素。

    • index(可选):当前元素的索引。

    • array(可选):原数组本身。

  • initialValue(可选):累加器的初始值。若未提供,则使用数组的第一个元素(此时数组不能为空,否则报错)。

工作原理:

  • 如果没有提供 initialValue,reduce 会从索引 1 开始执行回调函数,跳过第一个索引。如果提供 initialValue,从索引 0 开始。

  • 如果数组为空且没有提供 initialValue,会抛出 TypeError。

  • 如果数组只有一个元素且没有提供 initialValue,或者提供了 initialValue 但数组为空,则直接返回该唯一值或 initialValue。

示例:

1、无初始值求和

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr);
console.log(sum); 
初始状态:
数组:[1, 2, 3, 4]
当前索引:从第二个元素(索引 1)开始。
初始值:未提供 → 使用数组的第一个元素 1 作为初始值。第一次回调(索引 1,值 2):
累加器(acc):1(初始值)
当前值(curr):2
计算:1 + 2 = 3
返回值:3 → 成为下一次的累加器。第二次回调(索引 2,值 3):
累加器(acc):3
当前值(curr):3
计算:3 + 3 = 6
返回值:6 → 成为下一次的累加器。第三次回调(索引 3,值 4):
累加器(acc):6
当前值(curr):4
计算:6 + 4 = 10
返回值:10 → 最终结果。

2、有初始值求和

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + cur, 0);
console.log(sum); // 输出: 10
初始值 acc = 0
第1次: 0 + 1 = 1
第2次: 1 + 2 = 3
第3次: 3 + 3 = 6
第4次: 6 + 4 = 10 → 最终结果

3、找出最大数

const numbers = [10, 5, 25, 8, 30];
const max = numbers.reduce((acc, curr) => Math.max(acc, curr));
console.log(max); // 30

4、对象求和

const list = [{id: '1',date: '20250101',inMoney: '100',outMoney: '200'},{id: '2',date: '20250101',inMoney: '101',outMoney: '201'},{id: '3',date: '20250102',inMoney: '102',outMoney: '202'},{id: '4',date: '20250102',inMoney: '103',outMoney: '203'},
];const result = list.reduce((acc, curr) => {const date = curr.date;if (!acc[date]) {acc[date] = {date,inMoney: 0,outMoney: 0};}acc[date].inMoney += Number(curr.inMoney);acc[date].outMoney += Number(curr.outMoney);return acc;
}, {});
console.log(result);
/*
{"20250101": {"date": "20250101","inMoney": 201,"outMoney": 401},"20250102": {"date": "20250102","inMoney": 205,"outMoney": 405}
}
*/// 转换为数组形式
const resultArray = Object.values(result);
console.log(resultArray);
/*
[{"date": "20250101","inMoney": 201,"outMoney": 401},{"date": "20250102","inMoney": 205,"outMoney": 405}
]
*/

5、实现 group by 功能

function groupBy(array, callback) {return array.reduce((acc, item) => {const key = typeof callback === 'function'? callback(item): item[callback];if (!acc[key]) {acc[key] = [];}acc[key].push(item);return acc;}, {});
}// 示例用法
const people = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 25 },{ name: 'Charlie', age: 30 }
];// 按年龄分组
const groupedByAge = groupBy(people, 'age');
console.log(groupedByAge);
// 输出:
// {
//   "25": [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 25 }],
//   "30": [{ name: 'Charlie', age: 30 }]
// }

concat 合并

用于合并数组或字符串。

const newArray = oldArray.concat(value1, value2, ..., valueN)

特点:

  • 不会修改原数据

  • 返回合并后的新数据

  • 对于嵌套数组,只会进行一层的扁平化处理

示例:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1.concat(arr2);
console.log(arr3); // [1, 2, 3, 4, 5, 6]const arr = [1, 2];
const merged = arr.concat(3, [4, 5]);
console.log(merged); // 输出: [1, 2, 3, 4, 5]

虽然该方法能实现字符串连接功能,但在实际开发中,更推荐使用 + 或模板字符串这两种方式,因为它们的效率更高,书写也更简洁。

from 转换

能够把类数组对象或者可迭代对象转换为全新的、浅拷贝的数组实例。

Array.from(arrayLike[, mapFn[, thisArg]])
  • arrayLike:表示要转换为数组的类数组对象或者可迭代对象。

  • mapFn(此参数可选):这是一个映射函数,会对数组中的每个元素进行处理。

  • thisArg(此参数可选):在执行 mapFn 函数时使用的 this 值。

示例:

1、转换字符串为字符数组

const str = "hello";
const chars = Array.from(str);
console.log(chars); // 输出: ['h', 'e', 'l', 'l', 'o']

2、转换 Set 为数组并去重

const set = new Set([1, 2, 2, 3, 3, 3]);
const uniqueArray = Array.from(set);
console.log(uniqueArray); // 输出: [1, 2, 3]

3、转换 Map 为数组

const map = new Map([[1, 'a'],[2, 'b'],[3, 'c']
]);
const array = Array.from(map);
console.log(array); // 输出: [[1, 'a'], [2, 'b'], [3, 'c']]

4、使用映射函数处理元素

const numbers = [1, 2, 3];
const doubled = Array.from(numbers, x => x * 2);
console.log(doubled); // 输出: [2, 4, 6]

5、生成指定范围的数组

const range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range); // 输出: [1, 2, 3, 4, 5]// 等价于
const range = [];
for (let i = 0; i < 5; i++) {range.push(i + 1);
}
console.log(range);// 等价于
const range = [...Array(5)].map((_, i) => i + 1);
console.log(range);

树形结构

移除树形结构中符合条件的节点

根据属性和值查找匹配的节点

根据属性和值查找父节点

结构纵转横

class TreeUtils {/*** 移除树形结构中符合条件的节点* @param {Array} tree - 树形结构数组* @param {string} attr - 要匹配的属性名* @param {any} value - 要匹配的属性值* @param {string} childrenKey - 子节点数组的键名,默认为'children'* @returns {Array} 处理后的树形结构*/static removeNodesByAttr(tree, attr, value, childrenKey = 'children') {return tree.filter(node => {if (node[attr] === value) {return false;}if (node[childrenKey] && node[childrenKey].length > 0) {node[childrenKey] = this.removeNodesByAttr(node[childrenKey], attr, value, childrenKey);}return true;});}/*** 根据属性和值查找匹配的节点* @param {Array} tree - 树形结构数组* @param {string} attr - 要匹配的属性名* @param {any} value - 要匹配的属性值* @param {string} childrenKey - 子节点数组的键名,默认为'children'* @returns {Object|null} 匹配的节点,未找到时返回null*/static findNodeByAttr(tree, attr, value, childrenKey = 'children') {for (const node of tree) {if (node[attr] === value) {return node;}if (node[childrenKey] && node[childrenKey].length > 0) {const found = this.findNodeByAttr(node[childrenKey], attr, value, childrenKey);if (found) return found;}}return null;}/*** 根据属性和值查找父节点* @param {Array} tree - 树形结构数组* @param {string} attr - 要匹配的属性名* @param {any} value - 要匹配的属性值* @param {string} childrenKey - 子节点数组的键名,默认为'children'* @returns {Object|null} 父节点,未找到时返回null*/static findParentByAttr(tree, attr, value, childrenKey = 'children') {for (const node of tree) {if (node[childrenKey] && node[childrenKey].length > 0) {// 检查子节点中是否有匹配的节点for (const child of node[childrenKey]) {if (child[attr] === value) {return node;}}// 递归查找子树const found = this.findParentByAttr(node[childrenKey], attr, value, childrenKey);if (found) return found;}}return null;}/*** 树形结构纵转横(层级转水平结构)* @param {Array} tree - 树形结构数组* @param {string} childrenKey - 子节点数组的键名,默认为'children'* @returns {Array} 转换后的水平结构数组*/static treeToHorizontal(tree, childrenKey = 'children') {const result = [];const queue = [...tree];while (queue.length > 0) {const current = queue.shift();result.push(current);if (current[childrenKey] && current[childrenKey].length > 0) {queue.push(...current[childrenKey]);// 移除原始的children属性避免循环引用delete current[childrenKey];}}return result;}
}// 示例用法
const tree = [{id: 1,name: 'Root',children: [{id: 2,name: 'Child1',children: [{ id: 4, name: 'Grandchild1', children: [] }]},{ id: 3, name: 'Child2', children: [] }]}
];// 使用示例
console.log('找到的节点:', TreeUtils.findNodeByAttr(tree, 'id', 4));
console.log('父节点:', TreeUtils.findParentByAttr(tree, 'id', 4));
console.log('移除节点后的树:', TreeUtils.removeNodesByAttr(tree, 'id', 2));
console.log('纵转横后的结构:', TreeUtils.treeToHorizontal(tree));    

其他

Math 和 toFixed

// 丢弃小数部分,保留整数部分
parseInt(5/2) // 2// 向上取整,有小数就整数部分加1
Math.ceil(5/2) // 3// 四舍五入取整
Math.round(5/2) // 3// 向下取整
Math.floor(5/2) // 2// 随机数
Math.random() // 返回0-1之间的一个随机数,0.644678467601536// 获取随机整数
function getRandomNum (min, max) {return Math.floor(Math.random() * (max - min + 1) ) + min;
}// 使用 toFixed() 来操作小数点时,并不遵循四舍五入,而是四舍六入五看情况
var num1 = 1.15;
var num2 = 1.25;
console.log(num1.toFixed(1)) // 1.1
console.log(num2.toFixed(1)) // 1.3
// 并不能确认5到底是舍还是入,所以最好不要用该方法
console.log(num1.toFixed(5)) // 1.15000 用它来补0还是很好用的// 综上,想要以四舍五入的形式来操作小数点,正确方法如下
var num = 1.15;
var result = Math.round(num * 10) / 10 // 1.2

string 和 json 转换

// string 转 json对象
JSON.parse(string)  // 对象转 string
JSON.stringify(obj)  

拓展:

// 后端 java string 转 json
JSONObject obj = JSONObject.parseObject(string);// json 转 string
String str = obj.toJSONString();// 遍历 json 对象
Iterator<Entry<String,Object>> iterator = obj.entrySet().iterator();
while(iterator.hasNext()){Entry<String,Object> entry = iterator.next();String key = (String)entry.getKey();String value = (String)entry.getValue();
}

金额转千分位

formatCurrency(num) {if (num) {num = num.toString().replace(/,/g, "");num = parseFloat(num);num = num.toFixed(2);num = num.replace(/\B(?=(\d{3})+\b)/g, ",");} else {num = "0.00";}return num;
}

字符串替换

str.replace(/,/g , "")

判断对象是否等于 {}

Object.keys

function isEmptyObject(obj) {return Object.keys(obj).length === 0;
}const hasObject = { name: "John", age: 30 };
const emptyObject = {};
const undefinedObject = undefined;
const nullObject = null;console.log(isEmptyObject(hasObject)); // false
console.log(isEmptyObject(emptyObject)); // true
console.log(isNotEmptyObject(undefinedObject)); // 报错
console.log(isNotEmptyObject(nullObject)); // 报错

JSON.stringify

function isEmptyObject(obj) {return JSON.stringify(obj) === "{}";
}const myObject = { name: "John", age: 30 };
const emptyObject = {};
const undefinedObject = undefined;
const nullObject = null;console.log(isEmptyObject(myObject)); // false
console.log(isEmptyObject(emptyObject)); // true
console.log(isEmptyObject(undefinedObject)); // false
console.log(isEmptyObject(nullObject)); // false

hasOwnProperty

function isEmptyObject(obj) {for (let key in obj) {if (obj.hasOwnProperty(key)) {return false;}}return true;
}const myObject = { name: "John", age: 30 };
const emptyObject = {};
const undefinedObject = undefined;
const nullObject = null;console.log(isEmptyObject(myObject)); // false
console.log(isEmptyObject(emptyObject)); // true
console.log(isEmptyObject(undefinedObject)); // true
console.log(isEmptyObject(nullObject)); // true

Object.values

用于提取对象的所有可枚举属性的值,并返回一个由这些值组成的数组。

const person = {name: 'Alice',age: 30,city: 'New York'
};const values = Object.values(person);
console.log(values); // 输出: ['Alice', 30, 'New York']const data = {id: 1,scores: [85, 90, 95],details: {email: 'alice@example.com'}
};const values = Object.values(data);
console.log(values); // 输出: [1, [85, 90, 95], { email: 'alice@example.com' }]

非常规方法

!!~ 判断字符串是否包含

在JavaScript中,!!~ 是一种常见的技巧,通常用于将字符串中的某个字符是否存在于另一个字符串中进行判断。

具体来说,~ 是位运算符,它会将操作数的每一位取反。而! 是逻辑运算符,会对操作数进行逻辑非运算。

当我们使用!!~ 对字符串进行操作时,它的作用是判断第一个字符串是否包含第二个字符串。当第二个字符串存在于第一个字符串中时,位运算符~会返回一个非负整数,而逻辑非运算符!会将该整数转换为布尔值的true。如果第二个字符串不存在于第一个字符串中,则~会返回 -1,而!会将其转换为布尔值的false

示例:

const string1 = "Hello, world!";
const string2 = "world";console.log(!!~string1.indexOf(string2));  // true,因为 "world" 存在于 "Hello, world!" 中
console.log(!!~string1.indexOf("foo"));    // false,因为 "foo" 不存在于 "Hello, world!" 中

请注意,虽然!!~ 是一种常见的技巧,但它可能会使代码难以理解和维护。在实际开发中,建议使用更明确、易懂的方式进行判断。

~~ 把字符串转换成数字

const num = ~~'1' // 1 'number'
console.log(num, typeof(num));const num = ~~'0.6' // 0 'number'、const num = ~~'001.6' // 1 'number'、const num = ~~'1.2.3.4.56' // 0 'number'、const num = ~~'fff' // 0 'number'、const num = ~~'-1.6' // -1 'number'、const num = ~~null // 0 'number'const num = ~~NaN // 0 'number'const num = ~~undefined // 0 'number'const num = ~~new Date() // 1017234654 'number'

相关文章:

  • Android设备 显示充电速度流程
  • 掌握Git:版本控制与高效协作指南
  • netcore项目使用winforms与blazor结合来开发如何按F12,可以调出chrome devtool工具辅助开发
  • 深入浅出IIC协议 -- 第二篇:FPGA数字接口设计方法论
  • 基于Java在高德地图面查询检索中使用WGS84坐标的一种方法-以某商场的POI数据检索为例
  • Flutter 中的 async/await 和 Future
  • 全能视频处理工具介绍说明
  • 大语言模型 12 - 从0开始训练GPT 0.25B参数量 MiniMind2 补充 训练开销 训练步骤 知识蒸馏 LoRA等
  • JavaScript 性能优化实战指南
  • 《JVM如何判断一个对象可以被回收?图文详解GC Root算法》
  • 深度解析:Redis 性能优化全方位指南
  • Python操作PDF书签详解 - 添加、修改、提取和删除
  • AI量化交易是什么?它是如何重塑金融世界的?
  • 如何评估开源商城小程序源码的基础防护能力?
  • 蓝桥杯2300 质数拆分
  • 四:操作系统cpu调度之调度算法
  • JVM类加载机制
  • Java设计模式之桥接模式:从入门到精通
  • 1-3V升3.2V升压驱动WT7013
  • 利用ffmpeg截图和生成gif
  • 5月LPR下调:1年期、5年期以上品种均下调10个基点
  • 视频丨习近平在河南洛阳市考察调研
  • “当代阿炳”甘柏林逝世,创办了国内第一所残疾人高等学府
  • 北方今年首场高温过程开启,西北华北黄淮多地最高或达40℃
  • 西浦国际教育创新论坛举行,聚焦AI时代教育本质的前沿探讨
  • 纽约市长称墨海军帆船撞桥已致2人死亡,撞桥前船只疑似失去动力