在Javascript中通过函数获取所有继承属性

get all inherited properties by function in Javascript

本文关键字:继承 属性 获取 函数 Javascript      更新时间:2023-09-26

不使用函数,当我使用for (var prop in obj)时,它将显示对象中的所有值。然而,当我试图放入函数时,它只是向我显示对象中的第一个值,而不是向我显示第二个元素(studentID)。(

var target = document.getElementById("outputArea");
var outstring = " ";
var myObj = {
	name: "Nguyen Viet Tien",
	StudentID: "26813157",
};
function tellAll(obj) {
	var dis = " ";
	
	for(var prop in obj) {
		dis += "first property is" + prop + "with the content" + obj[prop] + "<br/>";	
		return dis;
	}
}
outstring += tellAll(myObj);
target.innerHTML = outstring;
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Eng1003 Workshop Code Week 04</title>
	<style>
		#outputArea {
			padding: .25em;
			border: solid black 2px;
			margin: 3em;			
			height: 20em;
			width: 20em;
			overflow-y: scroll;
			font-family: arial "sans serif";
			font-size: 1em;
			color: rgb(50, 50, 250);
			background-color: rgb(225,225,225) ;
		}
	</style>
</head>
<body>
	<div id="outputArea"></div>
</body>
</html>

返回语句位置错误

function tellAll(obj) {
    var dis = " ";
    for(var prop in obj) {
        dis += "first property is" + prop + "with the content" + obj[prop] + "<br/>";   
    }
    return dis;
}