JavaScript 判断对象是否存在字段
JavaScript About 530 wordsObject.keys
const obj1 = { name: "test" };
const obj2 = {};
console.log(Object.keys(obj1).length > 0); // true
console.log(Object.keys(obj2).length > 0); // false
简洁写法
!!Object.keys(obj).length
const isNotEmpty = !!Object.keys(obj).length;
判断指定字段
in
const obj = { name: "test" };
console.log("name" in obj); // true
console.log("toString" in obj); // true(原型链上的方法)
hasOwnProperty(只检查自身属性,推荐)
const obj = { name: "test" };
console.log(obj.hasOwnProperty("name")); // true
console.log(obj.hasOwnProperty("toString")); // false
Views: 8 · Posted: 2026-05-21
———         Thanks for Reading         ———
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...