猪八戒面试前端题

来源:互联网 发布:傲剑金蛇剑法升级数据 编辑:程序博客网 时间:2024/04/27 15:21

1.js如何判断一个对象为数组?

方法一 instanceof

instanceof 用于判断一个变量是否某个对象的实例

a instanceof b?alert(“true”):alert(“false”)
//注意b值是你想要判断的那种数据类型,不是一个字符串,比如Array

举个栗子:

var a=[]; console.log(a instanceof Array) //返回true

方法二 constructor
在W3C定义中的定义:constructor 属性返回对创建此对象的数组函数的引用,就是返回对象相对应的构造函数。

  (a.constructor == Array) // a实例所对应的构造函数是否为Array? true or false

较为严谨并且通用的方法:

function isArray(object){
return object && typeof object===’object’ &&
Array == object.constructor; }

方法三 特性判断法

function isArray(object){
return object && typeof object===’object’ &&
typeof object.length===’number’ &&
typeof object.splice===’function’ &&
//判断length属性是否是可枚举的 对于数组 将得到false
!(object.propertyIsEnumerable(‘length’)); } 复制代码 有length和splice并不一定是数组,因为可以为对象添加属性,而不能枚举length属性,才是最重要的判断因子。

方法四 最简单的方法

对于这种方法,以下有几个链接可供参考解释:

http://blog.csdn.net/zhangw428/article/details/4171630

http://my.oschina.net/sfm/blog/33197

http://openxtiger.iteye.com/blog/1893378

function isArray(o) {
return Object.prototype.toString.call(o) === ‘[object Array]‘; }

2.js如何将任意字符串转换成字符数组

字符串转数组

> var str = "adsfasdfasdf";> console.log(str.split(""));> console.log(str.replace(/(.)(?=[^$])/g,"$1,").split(","));> //正则表达式--匹配任意字符除开$将其替换成$1变量(指定的任意字符本身)加上,

数组转字符串

> var array = str.split(""); > console.log(array.join(""));> console.log(array.toString().replace(/,/g,""));

3.js操作数组的方法

concat() 连接两个或更多的数组,并返回结果。
join() 把数组的所有元素放入一个字符串。元素通过指定的分隔符进行分隔。
pop() 删除并返回数组的最后一个元素
push() 向数组的末尾添加一个或更多元素,并返回新的长度。
reverse() 颠倒数组中元素的顺序。
shift() 删除并返回数组的第一个元素
slice() 从某个已有的数组返回选定的元素
sort() 对数组的元素进行排序
splice() 删除元素,并向数组添加新元素。
toSource() 返回该对象的源代码。
toString() 把数组转换为字符串,并返回结果。
toLocaleString() 把数组转换为本地数组,并返回结果。
unshift() 向数组的开头添加一个或更多元素,并返回新的长度。
valueOf() 返回数组对象的原始值

4.css布局右侧固定,左侧自适应

<div class="ff">        <div class="box left"></div>        <div class="box right"></div></div>//1.固定区域绝对定位,自适应区域设置margin.left{    margin-left: 310px;    width:100%;}.right{    position: absolute;    left: 0;    top: 0;    width: 300px;}//2.float加margin.left{    float: left;    margin-left: -310px;    width: 100%;}.right{    float: right;    width: 300px;}//3.标准处理方式,ie7以下不兼容,table加浮动.ff{    display: table;    width: 100%;}.left{    display: table-cell;    width: 100%;}.right{    width: 300px;    float: right;}
1 0
原创粉丝点击