如何在 JavaScript 中获取对象的属性值?
有一些方法可以查找对象的属性值,例如 `Object.values()`,但是使用此方法过程会很冗长。
我们可以借助 `_.values()` 函数轻松查找对象的属性值,这是一个内置方法,属于 underscore.js(一个提供多种功能的 JavaScript 库)。
`_.values()` 方法无需循环即可获取值,它是查找对象属性值的直接方法。
语法
_.values( object )
参数 - 此函数只接受一个参数,即对象。对象类似于数组,具有键值对,但它不是数组。
示例 1
以下是一个从对象中检索值的示例:
<!DOCTYPE html>
<html>
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
var obj = {"name": 'Abcd kumar',age: 47, contact:9893444666, "Organization":'Spacex' }
var res = JSON.stringify(_.values(obj)); // we are using stringify because we want to print the value in page not in console.
document.write((res));
</script>
</body>
</html>
示例 2
在这个例子中,我们使用 `object.values()` 函数打印对象的属性值。
<!DOCTYPE html>
<html>
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
var userDetails = {name: 'Aman Kumar',state:"Jharkhnad", work:'Technical Writer', company:"TutorialsPoint" };
for(let value of Object.values(userDetails)){
document.write(" " + value + " ");
}
</script>
</body>
</html>
示例 3
让我们来看另一个例子:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
<script type="text/javascript">
var details = _.values({
Name: "Vivek",
Address: "Noida Up",
Mobile: "+91 9876452301",
Email: "tutorialspoint@gmail.com",
});
//console.log(key);
for(let value of details){
document.write(" " + value + " ");
}
</script>
</body>
</html>
示例 4
这是一个示例,我们将对象的属性值以数组格式打印出来:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"
></script>
</head>
<body>
<script type="text/javascript">
var details = _.values({
Name: "Vivek",
Address: "Noida",
Mobile: "+91 9876452301",
Email: "tutorialspoint@gmail.com",
});
var object = _.values({
name: "Aman Kumar",
Address: "Hyderabad",
Mobile: "+91 8252240532",
});
//console.log(key);
document.write("[");
for (let value of details) {
document.write(" " + value + " ");
} // here we are using for loop and documet.write() to display the value in page.
document.write("]");
document.write("[");
for (let x of object[2]) {
document.write(x); // get the third item from the list returned as well
}
document.write("]");
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP