关于JavaScript的学习(五)——引用类型

第五章

  • Object类型
var person = new Object();  //或 var person={};
person.name = "Nicholas";
person.age = 29;

//与上面相同,为对象字面量表示法
var person = {
    name : "Nicholas",
    age : 29
}

alert(person["name"]);        //"Nicholas"
alert(person.name);           //"Nicholas"
var propertyName = "name";
alert(person[propertyName]);  //"Nicholas"
//建议用点表示法
  • Array类型
var colors = ["red","blue","green"];
alert(colors.length);     //3

#length长度可以设置
var colors = ["red","blue","green"];
colors.length = 2;
alert(colors[2]);    //undefined

#toLocaleString()和toString()
var person1 = {
    toLocaleString : function () {
        return "Nikolaos";
    },

    toString : function() {
        return "Nicholas";
    }
};
var person2 = {
    toLocaleString : function () {
        return "Grigorios";
    },

    toString : function() {
        return "Greg";
    }
};
var people = [person1, person2];
alert(people);                      //Nicholas,Greg
alert(people.toString());           //Nicholas,Greg
alert(people.toLocaleString());     //Nikolaos,Grigorios

#join()
var colors = ["red", "green", "blue"];
alert(colors.join(",")); //red,green,blue
alert(colors.join("||")); //red||green||blue

#push()和pop()   栈方法
var colors = new Array(); //create an array
var count = colors.push("red", "green"); //push two items
alert(count);  //2
count = colors.push("black");//push another item on
alert(count);  //3
var item = colors.pop();//get the last item
alert(item);   //"black"
alert(colors.length);  //2

#shift()和unshift()     队列方法
var colors = new Array(); //create an array
var count = colors.push("red", "green");  //push two items
alert(count);  //2
count = colors.push("black");  //push another item on
alert(count);  //3
var item = colors.shift(); //get the first item
alert(item);   //"red"
alert(colors.length);  //2

var colors = new Array();    //create an array
var count = colors.unshift("red", "green");    //push two items
alert(count);  //2
count = colors.unshift("black"); //push another item on
alert(count);  //3
var item = colors.pop();  //get the first item
alert(item);   //"green"
alert(colors.length);  //2

#resverse()和sort()   重排序方法
var values = [1, 2, 3, 4, 5];
values.reverse();
alert(values);       //5,4,3,2,1

function compare(value1, value2) {
    if (value1 < value2) {
        return 1;
    } else if (value1 > value2) {
        return -1;
    } else {
        return 0;
    }
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
alert(values);    //15,10,5,1,0

//或将compare改为
function compare(value1, value2) {
    return value2-value1;
}

#concat()
var colors = ["red", "green", "blue"];
var colors2 = colors.concat("yellow", ["black", "brown"]);
alert(colors);     //red,green,blue        
alert(colors2);    //red,green,blue,yellow,black,brown

#slice()
//只有一个参数的情况,slice返回从该参数指定位置开始到当前数组末尾的左右项
//如果有两个参数,该方返回起始和结束位置之间的项——但不包括结束位置的项
var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
alert(colors2);   //green,blue,yellow,purple
alert(colors3);   //green,blue,yellow

#splice()
/*删除:删除任意数量的项,2个参数:要删除的第一项的位置、要删除的项数
 *插入:向指定位置插入任意数量的项,3个参数:起始位置、0、要插入的项数
 *替换:向指定位置插入任意数量的项,3个参数:起始位置、要删除的项数、要插入的任意数量的项
 *始终会返回一个数组,数组中包含从原始数组中删除的项(如果没有则返回空数组)
 */
var colors = ["red", "green", "blue"];
var removed = colors.splice(0,1); //删除第一项
alert(colors); //green,blue
alert(removed);  //red,返回的数组中只包含一项

removed = colors.splice(1, 0, "yellow", "orange");  //从位置1开始插入两项
alert(colors); //green,yellow,orange,blue
alert(removed); //返回空数组

removed = colors.splice(1, 1, "red", "purple"); //插入两项,删除一项
alert(colors); //green,red,purple,orange,blue
alert(removed); //yellow,返回的数组中只包含一项

#indexOf()和lastIndexOf()      位置方法
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4));        //3
alert(numbers.lastIndexOf(4));    //5
alert(numbers.indexOf(4, 4));     //5
alert(numbers.lastIndexOf(4, 4)); //3       
var person = { name: "Nicholas" };
var people = [{ name: "Nicholas" }];
var morePeople = [person];
alert(people.indexOf(person));     //-1
alert(morePeople.indexOf(person)); //0

##迭代方法:对数组中的每一项运行给定的函数
#every()和some()
//every():如果给定函数对每一项都返回true,则返回true
//some():如果给定函数对任意一项返回true,则返回true
var numbers = [1,2,3,4,5,4,3,2,1];

var everyResult = numbers.every(function(item, index, array){
    return (item > 2);
});
alert(everyResult);       //false

var someResult = numbers.some(function(item, index, array){
    return (item > 2);
});
alert(someResult);       //true

#filter()
//返回给定函数会返回true的项组成的数组
var numbers = [1,2,3,4,5,4,3,2,1];
var filterResult = numbers.filter(function(item, index, array){
    return (item > 2);
});
alert(filterResult);   //[3,4,5,4,3]

#map()
//返回每次给定函数调用的结果组成的数组
var numbers = [1,2,3,4,5,4,3,2,1];
var mapResult = numbers.map(function(item, index, array){
    return item * 2;
});
alert(mapResult);   //[2,4,6,8,10,8,6,4,2]

#forEach()
//没有返回值
var numbers = [1,2,3,4,5,4,3,2,1];
numbers.forEach(function(item,index,array){
    //执行某些操作
});
##

#reduce()和reduceRight()
//reduce从第一项开始,reduceRight从最后一项
var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
    return prev + cur;
});
alert(sum);

##Number类型
var numberObject = new Number(10);
var numberValue = 99;

#toString() using a radix
alert(numberObject.toString());       //"10"
alert(numberObject.toString(2));      //"1010"
alert(numberObject.toString(8));      //"12"
alert(numberObject.toString(10));     //"10"
alert(numberObject.toString(16));     //"a"

#toFixed()
alert(numberObject.toFixed(2));    //outputs "10.00"

#toPrecision()
numberObject = new Number(99);
alert(numberObject.toPrecision(1));    //"1e+2"
alert(numberObject.toPrecision(2));    //"99"
alert(numberObject.toPrecision(3));    //"99.0"

alert(typeof numberObject);   //object
alert(typeof numberValue);    //number
alert(numberObject instanceof Number);  //true
alert(numberValue instanceof Number);   //false
##
  • 字符串类型
#slice()、substr()、substring()
var stringValue = "hello world";
alert(stringValue.slice(3));        //"lo world"
alert(stringValue.substring(3));    //"lo world"
alert(stringValue.substr(3));       //"lo world"
alert(stringValue.slice(3, 7));     //"lo w"
alert(stringValue.substring(3,7));  //"lo w"
alert(stringValue.substr(3, 7));    //"lo worl"

alert(stringValue.slice(-3));         //"rld"
alert(stringValue.substring(-3));     //"hello world"
alert(stringValue.substr(-3));        //"rld"
alert(stringValue.slice(3, -4));      //"lo w"
alert(stringValue.substring(3, -4));  //"hel"
alert(stringValue.substr(3, -4));     //"" (empty string)

#indexOf()和lastIndexOf()
var stringValue = "hello world";
alert(stringValue.indexOf("o"));         //4
alert(stringValue.lastIndexOf("o"));     //7
alert(stringValue.indexOf("o", 6));         //7
alert(stringValue.lastIndexOf("o", 6));     //4

var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
var positions = new Array();
var pos = stringValue.indexOf("e");
while(pos > -1){
    positions.push(pos);
    pos = stringValue.indexOf("e", pos + 1);
}
alert(positions);    //"3,24,32,35,52"

#trim()
var str="    Hello World     ";
var trimmedStr=str.trim();
alert(str);//"    Hello World     "
alert(trimmedStr);//"Hello World"

#字符串大小写转换
var stringValue = "hello world";
alert(stringValue.toLocaleUpperCase());  //"HELLO WORLD"
alert(stringValue.toUpperCase());        //"HELLO WORLD"
alert(stringValue.toLocaleLowerCase());  //"hello world"
alert(stringValue.toLowerCase());        //"hello world"

#字符串的模式匹配
var text = "cat, bat, sat, fat"; 
var pattern = /.at/;

var matches = text.match(pattern);        
alert(matches.index);        //0
alert(matches[0]);           //"cat"
alert(pattern.lastIndex);    //0

var pos = text.search(/at/);
alert(pos);   //1

var result = text.replace("at", "ond");
alert(result);    //"cond, bat, sat, fat"

result = text.replace(/at/g, "ond");
alert(result);    //"cond, bond, sond, fond"

result = text.replace(/(.at)/g, "word ($1)");
alert(result);    //word (cat), word (bat), word (sat), word (fat)

function htmlEscape(text){
    return text.replace(/[<>"&]/g, function(match, pos, originalText){
        switch(match){
            case "<":
                return "&lt;";
            case ">":
                return "&gt;";
            case "&":
                return "&amp;";
            case "\"":
                return "&quot;";
        }             
    });
}

alert(htmlEscape("<p class=\"greeting\">Hello world!</p>")); //&lt;p class=&quot;greeting&quot;&gt;Hello world!&lt;/p&gt;

var colorText = "red,blue,green,yellow";
var colors1 = colorText.split(",");      //["red", "blue", "green", "yellow"]
var colors2 = colorText.split(",", 2);   //["red", "blue"]
var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""]

#localeCompare()
var stringValue = "yellow";       
alert(stringValue.localeCompare("brick"));  //1
alert(stringValue.localeCompare("yellow")); //0
alert(stringValue.localeCompare("zoo"));    //-1

//preferred technique for using localeCompare()
function determineOrder(value) {
    var result = stringValue.localeCompare(value);
    if (result < 0){
        alert("The string 'yellow' comes before the string '" + value + "'.");
    } else if (result > 0) {
        alert("The string 'yellow' comes after the string '" + value + "'.");
    } else {
        alert("The string 'yellow' is equal to the string '" + value + "'.");
    }
}

determineOrder("brick");
determineOrder("yellow");
determineOrder("zoo");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值