从面试题学习Javascript——基础知识
题目:
try{
var data1 = [4,5,6,7,8,9,10,11,12];
var data2 = {
"a": 4,
"b": 5,
"c": 6
};
console.group(data1);
each(data1, function(o){
if( 6 == this )
return true;
else if( 8 == this )
return false;
console.log(o + ": \"" + this + "\"");
});
console.groupEnd();
/*------[执行结果]------
1: "4"
2: "5"
4: "7"
------------------*/
console.group(data2);
each(data2, function(v, n){
if( 5 == this )
return true;
console.log(n + ": \"" + v + "\"");
});
console.groupEnd();
/*------[执行结果]------
a: "4"
c: "6"
------------------*/
}catch(e){
console.error("执行出错,错误信息: " + e);
}
知识点:
(1)对象直接量和JSON之间的区别
对象直接量:对象直接量(也称为对象初始化程序)是由一个列表构成的,这个列表的元素是用冒号分隔的属 性/值对,元素之间用逗号隔开的,整个列表包含花括号之中。例如
var data2 = {a: 4,b: 5,c: 6};
JSON:JSON 语法是 JavaScript 对象表示法语法的子集。JSON 数据的书写格式是:名称/值对。名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值:
var data2 = {"a": 4,"b": 5,"c": 6};
(2)for(.. in ...)的用法
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
for (variable in object) {
...
}
variable :A different property name is assigned to variable on each iteration.
object:Object whose enumerable properties are iterated.
在本例中利用for(variable in object)来遍历JSON中的属性
(3)call函数
There are two noninherited methods for functions: apply() and call() . These methods both call the function within a specific scope, effectively setting the value of the thisobject inside the function body. The apply() method accepts two arguments: the scope in which to run the function, and an array of
arguments. This second argument may be an instance of Array, but it can also be the arguments object.
call()和function()的用途都是在特定的作用域中调用函数,实际就是设置函数体内this对象的值。apply()方法接受两个参数:一个是在其中运行函数的作用域,另一 个是参数数组。对于call()方法而言,第一个参数是作用域没有变化,变化的只是其余的参数都是直接传递给函数的。
答案:
<!DOCTYPE html>
<html>
<head>
<style type="text/css" rel="stylesheet">
</style>
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
var each=function(obj,fn){
if(obj instanceof Array)
{
for(var i=0;i<obj.length;i++)
{
if(fn.call(obj[i],i+1)==false)
{
i=obj.length;
}
}
}
else
{
for(propertyName in obj)
{
fn.call(obj[propertyName],obj[propertyName],propertyName);
}
}
}
window.onload=function()
{
try{
var data1 = [4,5,6,7,8,9,10,11,12];
var data2 = {
"a": 4,
"b": 5,
"c": 6
};
console.group(data1);
each(data1, function(o){
if( 6 == this )
return true;
else if( 8 == this )
return false;
console.log(o + ": \"" + this + "\"");
});
console.groupEnd();
/*------[执行结果]------
1: "4"
2: "5"
4: "7"
------------------*/
console.group(data2);
each(data2, function(v, n){
if( 5 == this )
return true;
console.log(n + ": \"" + v + "\"");
});
console.groupEnd();
/*------[执行结果]------
a: "4"
c: "6"
------------------*/
}catch(e){
console.error("执行出错,错误信息: " + e);
}
}
</script>
</html>