IVYGOU / JavaScript

Learning Notes for JavaScript
0 stars 0 forks source link

如何使用方括号表示法来取得给定属性的值? #1

Open IVYGOU opened 8 years ago

IVYGOU commented 8 years ago
function createComparisonFunction(propertyName) {
  return function(object1, object2) {
    var value1 = object1[propertyName];
    var value2 = object2[propertyName]; //使用方括号表示法来取得给定属性的值
    if (value1 < value2) {
      return -1;
    } else if (value1 > value2) {
      return 1;
    } else(value1 = value2) {
      return 0;
    }
  };
}
var data=[{name:"Mike",age:21},{name:"Ivy",age:25}];
data.sort(createComparisonFunction("name"));
console.log(data[0].name);//Ivy
data.sort(createComparisonFunction("age"));
console.log(data[0].name);//Mike
IVYGOU commented 8 years ago

方括号表示的属性可以是变量,点表示的属性值是固定的不可变。