JavaScript面试题121-130
每日坚持学10道题
121. 求一个字符串的字节长度
[问答题]
编写一个方法 求一个字符串的字节长度。
来自:前端工程师练习卷
参考:
// 假设:一个英文字符占用一个字节,一个中文字符占用两个字节。
function GetBytes(str) {
var len = str.length;
var bytes = len;
for (var i = 0; i < len; i++) {
if (str.charCodeAt(i) > 255) bytes++;
}
return bytes;
}
console.log("你好,as");
console.log(GetBytes("你好,as")); // 7
参考调试: 代码地址
122. 数组去重(重点)
[问答题]
编写一个方法 去掉一个数组的重复元素
来自:前端工程师练习卷
参考:
// ES6中的Set方法
function unique(arr) {
return Array.from(new Set(arr))
}
var arr = [1, 1, 'true', 'true', true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN, 'NaN', 0, 0, 'a', 'a', {}, {}];
console.log(unique(arr))
//[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}]
// 利用filter
function unique(arr) {
return arr.filter(function (item, index, arr) {
//当前元素,在原始数组中的第一个索引==当前索引值,否则返回当前元素
return arr.indexOf(item, 0) === index;
});
}
var arr = [1, 1, 'true', 'true', true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN, 'NaN', 0, 0, 'a',
'a', {}, {}];
console.log(unique(arr))
//[1, "true", true, 15, false, undefined, null, "NaN", 0, "a", {…}, {…}]
其他方法: 请点击访问
123. this的应用
[问答题]
写出 2 个使用 this 的典型应用。
来自:前端工程师练习卷
参考:
- 在 html 元素事件属性中使用,如:
<input type=”button” onclick=”showInfo(this);” value=”点击一下”/>
- 构造函数
function Animal(name, color) { this.name = name; this.color = color; }
124. DOM
[问答题]
如何显示/隐藏一个 DOM 元素?
来自:前端工程师练习卷
参考:
el.style.display = "";
el.style.display = "none";
el 是要操作的 DOM 元素。
125. 检测一个变量是String
类型
[问答题]
JavaScript 中如何检测一个变量是一个 String 类型?请写出函数实现。
来自:前端工程师练习卷
参考:
String 类型有两种生成方式:
(1)Var str = “hello world”;
(2)Var str2 = new String(“hello world”);
function IsString(str) {
return (typeof str == "string" || str.constructor == String);
}
var str = "";
console.log(IsString(1)); // false
console.log(IsString(str)); // true
console.log(IsString(new String(str))); // true
126. 数据类型
[问答题]
JavaScript 有哪几种数据类型。
来自:前端工程师练习卷
答案:
简单:Number,Boolean,String,Null,Undefined
复合:Object,Array,Function
127. 标签
[问答题]
下面 css 标签在 JavaScript 中调用应如何拼写,border-left-color,-moz-viewport。
来自:前端工程师练习卷
参考:
borderLeftColor
mozViewport
128. 原型原型链
[填空题]
使用 for in 循环数组中的元素会枚举原型链上的所有属性,过滤这些属性的方式是使
用 1 函数
来自:阿里巴巴前端开发工程师笔试
答案:hasOwnProperty
129. alert换行
[问答题]
如何控制 alert 中的换行。
来自:前端工程师练习卷
参考:
\n alert(“p\np”);
130. js 的 class
[问答题]
js 中如何定义 class,如何扩展 prototype?
来自:前端工程师练习卷
参考:
Ele.className = “***”; //***在 css 中定义,形式如下:.*** {···}
A.prototype.B = C;
A 是某个构造函数的名字;
B 是这个构造函数的属性;
C 是想要定义的属性的值。
今天的基础题完成