A. "string"
B. "function"
C. "object"
D. "null"
A. 输入:typeof {"x":1} 输出:"object"
B. 输入:typeof 1 输出:"number"
C. 输入:typeof [{x:1}] 输出:"array"
D. 输入:typeof NaN 输出:"number"
A. undefined
B. null
C. array
D. object
A. Boolean
B. undefined
C. Symbol
D. Array
A. 数据类型分为基本数据类型和引用数据类型
B. JavaScript一共有8种数据类型
C. Object是引用数据类型,且只存储于堆(heap)中
D. BigInt是可以表示任意精度整数的基本数据类型,存储于栈(stack)中
答案
DCADC
A. null instanceof Object
B. null === undefined
C. null == undefined
D. NaN == NaN
A. Symbol.for('a') === Symbol.for('a')
B. Symbol('a') === Symbol('a')
C. NaN === NaN
D. {} === {}
var a = 1;
var b = [];
var c = '';
var d = true;
A. (a || b) === true
B. (b && c) === true
C. (c && d) === true
D. (d || a) === true
A. T
B. F
A. console.log([] === []);
B. console.log(undefined == 0);
C. console.log(undefined == false);
D. console.log(false == '');
A. console.log("12" === 12)
B. console.log (NaN === NaN)
C. console.log (typeof(null) === typeof(window))
D. console.log ([1,2,3] === [1,2,3])
注意浏览器环境与node环境的差别,比如C选项
A. Number('a') == Number('a')
B. -1 == true
C. 3 + '2' === 5
D. ![] == ''
答案
CADADCD
A. Math.round(7.25)
B. Math.ceil(7.25)
C. round(7.25)
D. Math.rnd(7.25)
A. Math.floor(Math.random()*6)
B. Math.floor(Math.random()*10)
C. Math.floor(Math.random()*11)
D. Math.ceil(Math.random()*10)
A. Math.floor(Math.random()*6)
B. Math.floor(Math.random()*7)
C. Math. floor(Math.random()*8)
答案
A CD(注意D) C
A. T
B. F
A. match()
B. indexOf()
C. search()
D. concat()
答案
A BC
A. {name:"xiaoming",age,"student"}
B. {"name":"xiaoming","age":"student"}
C. {"xiaoming","student"}
D. ["xiaoming","student"]
const fn = function(){}
const res = JSON.stringify(fn)
const num = 123
const res = JSON.stringify(num)
const res = JSON.stringify(NaN)
const b = true
const res = JSON.stringify(b)
A. 'function'、'123'、'NaN'、'true'
B. undefined、'123'、undefined、'true'
C. undefined、'123'、'null'、'true'
D. undefined、'123'、'null'、undefined
答案
BC
A. push
B. concat
C. sort
D. shift
A. slice
B. splice
C. sort
D. unshift
A. push
B. pop
C. shift
D. unshift
A. push
B. pop
C. unshift
D. splice
A. concat
B. splice
C. slice
D. join
A. concat
B. shift
C. filter
D. map
A. push
B. slice
C. splice
D. sort
// (1)
const newNums = Array.from(new Set(nums))
// (2)
const newNums = nums.filter((n, i) => {
return nums.indexOf(n) === i
})
// (3)
const newNums = nums.forEach((n, i) => {
return nums.indexOf(n) === i
})
// (4)
const newNums = nums.reduce((acc, n, i) => {
return [].concat(acc, nums.indexOf(n) === i ? n : []
)
})
A. (1)、(2)、(3)、(4)
B. (1)、(3)、(4)
C. (1)、(2)、(4)
D. (1)、(4)
答案
BAABB
BBC
A. 123
B. 123a
C. d123
D. 123def
A. test
B. match
C. exec
D. compile
A. str.replace(`/\s*/g,""`)
B. str.replace(`/^\s|\s$/g,""`)
C. str.replace(`/^\s*/, ""`)
D. str.replace(`/(\s*$)/g, ""`)
答案
CBA
A. encodeURI
B. parseFloat
C. round
D. eval
A. 遵循严格模式:"use strict"
B. 将js脚本放在页面顶部,加快渲染页面
C. 将js脚本成组打包,减少请求,尽量减少使用闭包
D. 使用非阻塞方式下载js脚本,最小化重绘(repaint)和回流(reflow)
A. parseFloat方法:该方法将一个字符串转换成对应的小数
B. isNaN方法:该方法用于检测参数是否为数值型,如果是,返回true,否则,返回false。
C. escape方法: 该方法返回对一个字符串编码后的结果字符串
D. eval方法:该方法将某个参数字符串作为一个JavaScript执行题
A. chrome
B. Safari
C. 搜狗浏览器
D. Firefox
// A
var formatDate=getDate()
// B
var formatDate = new Date()
// C
var formatDate = function (date) {
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
return y + '-' + m + '-' + d;
};
// D
var formatDate = function (date) {
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? '0' + m : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
return y + '-' + m + '-' + d;
};
A. 需要对元素进行复杂的操作时,可以先隐藏(display:"none"),操作完成后再显示
B. 需要创建多个DOM节点时,使用DocumentFragment创建完后一次性的加入document
C. 尽量避免用table布局(table元素一旦触发回流就会导致table里所有的其它元素回流)
D. 尽量不要使用 css 属性简写,如:用border-width, border-style, border-color代替border
答案
CBBDDD
A. eval
B. apply
C. bind
D. call
A. 在使用new实例化对象时, this指向这个实例对象
B. 将对象的方法赋值给变量A。执行A()时 该方法中的this指向这个对象。
C. 在函数定义时,this指向全局变量
D. 在浏览器下的全局范围内,this指向全局对象
A. call与apply都属于Function.prototype的一个方法,所以每个function实例都有call、apply属性
B. 两者传递的参数不同,call函数第一个参数都是要传入给当前对象的对象,apply不是
C. apply传入的是一个参数数组,也就是将多个参数组合成为一个数组传入
D. call传入的则是直接的参数列表。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
答案
AAB
// (1)
function getName() {
name = 'javascript'
}
getName()
// (2)
const elements = {
button: document.getElementById('button')
};
function removeButton() {
document.body.removeChild(elements.button);
}
removeButton()
// (3)
let timer = setInterval(() => {
const node = document.querySelector('#node')
if(node) {
clearInterval(timer)
}
}, 1000);
A. (1)、(2)、(3)
B. (2)、(3)
C. (1)、(3)
D. (1)、(2)
A. 没有清理的DOM元素引用
B. 被遗忘的定时器
C. 事件侦听没有移除
D. 局部变量不用时,没有设为null
A. 增加一定的内存消耗
B. 使用不当可能会导致内存泄漏
C. 可以使用闭包模拟私有方法
D. 闭包会改动对象的原型链
答案
DDD
A. 原型链继承
B. 构造函数继承
C. 组合继承
D. 关联继承
A. T
B. F
A. 通过原型链继承的属性和对象自己定义的属性等效
B. 通过原型链可以模拟对象的私有属性
C. 在对象上访问不存在的属性时,会依次遍历整条原型链
D. 所有 JavaScript 中的对象都是位于原型链顶端的 `Object` 的实例
答案
DBC
A. jsonp
B. cookie
C. localStorage
D. sessionStorage
答案
A
A. event.preventDefault()
B. event.prevent()
C. event.drag()
D. event.drop()
A. mouseover
B. click
C. mouseleave
D. mousemove
A. stopDeafault()
B. stopPropagation()
C. preventDefault()
D. preventDefaultEven()
目标 -> 捕获 -> 冒泡
冒泡 -> 目标 -> 捕获
目标 -> 冒泡 -> 捕获
捕获 -> 目标 -> 冒泡
A. onchange:用户改变域的内容
B. onkeypress:某个键盘的键被按下或按住
C. onmousedown:某个鼠标按键被按下
D. onblur:元素获得焦点
答案
ACCDD
A. parentObj.firstChild
B. parentObj.children
C. neborNode.previousSibling
D. neborNode.siblings
A. appendChild(parentNode,newNode);
B. append(parentNode,newNode);
C. parentNode.append(newNode);
D. parentNode.appendChild(newNode);
A. Array
B. Object
C. String
D. Function
A. appendChild(parentNode,newNode);
B. append(parentNode,newNode);
C. parentNode.append(newNode);
D. parentNode.appendChild(newNode);
答案
DDBD
outline
visiblity
font-size
background-color
答案
C
A. 每隔60秒调用一次updateClock()
B. 每隔60毫秒调用一次updateClock()
C. 每隔60分钟调用一次updateClock()
D. 每分钟调用60次updateClock()
A. Geolocation.watchPosition()
B. Geolocation.getCurrentPosition()
C. Geolocation.getPosition()
D. Geolocation.Position()
A. 等待1000秒后,再弹出一个对话框
B. 等待1秒钟后弹出一个对话框
C. 每隔一秒钟弹出一个对话框
D. 语句报错,语法有问题
答案
BBC
A. 箭头函数没有原型属性
B. 箭头函数不绑定this,会捕获其所在的上下文的this值,作为自己的this值
C. 箭头函数可以作为构造函数,使用new
D. 箭头函数不绑定arguments,取而代之用rest参数解决
A. 函数体内this的指向是定义时所在的对象,而不是使用时所在的对象
B. 箭头函数内不能使用arguments对象
C. 箭头函数不能使用yield命令
D. 可以使用new创建一个箭头函数的实例
答案
CD
Promise.all([]).then((res) => {
console.log('all');
});
Promise.race([]).then((res) => {
console.log('race');
});
A. all 和 race 都会被输出
B. all 和 race 都不会被输出
C. all 会被输出,而 race 不会被输出
D. all 不会被输出,race 会被输出
A. Promise
B. Generator
C. async
D. Proxy
A. Pending
B. Pause
C. Fulfilled
D. Rejected
答案
CDB
let [a,b, c,d, e] = "hello";
A. e = "hello";
B. 其它都为undefined
C. 当中 a = "h", b = "e";
D. 语法报错
答案
C
A. push
B. concat
C. splice
D. map
A. const a = 0xa1
B. const a = 076
C. const a = 0b21
D. const a = 7e2
(1)function
(2) object
(3) null
(4) array
(5) NaN
(6) bigint
(7) regexp
(8) undefined
A. (1)、(2)、(3)、(4)、(5)、(6)、(7)、(8)
B. (1)、(2)、(3)、(8)
C. (1)、(2)、(8)
D. (1)、(2)、(6)、(8)
A. typeof 'string'
B. String('string').toString()
C. 'string'.split('').sort().join('')
D. (function(string){return string})('string')
E. JSON.parse('{"string":"string"}').string
A. parseInt(46.8) `==` parseFloat(46.8)
B. NaN `!==` NaN
C. isNaN('abc') `==` NaN
D. typeof NaN `===` 'number'
A. Array.from(A)
B. [].slice.apply(A)
C. [...A]
D. [].map.call(A, o => o)
A. null == undefined
B. null === undefined
C. null === null
D. NaN == null
E. NaN === NaN
F. Infinity + 1 !== Infinity
答案
AC ABD D ABDE BD ABCD AC
function Person() { } var person = new Person();
A. 每一个原型都有一个constructor属性指向关联的构造函数。
B. 每一个对象都有一个prototype属性。
C. Object.getPrototypeOf(person) === Person.prototype
D. person.constructor === Person
A. process.nextTick
B. promise
C. setTimeout
D. setInterval
答案
ACD AB
A. let声明的变量值和类型都可以改变
B. const声明的常量不可以改变
C. 两者都不存在变量提升,同时存在暂时性死区,只能在声明的位置后面使用
D. const可以先声明再初始化,可以后赋值
A. Promise.all在所有给定的promise都fulfilled后才返回结果
B. Promise.race在给定的promise中,某个fulfilled后才返回结果
C. promise.then的回调函数中,可以返回一个新的promise
D. 对于一个向后台获取数据已经产生结果的promise:p1,再次调用p1.then,不会去重新发起请求获取数据
答案
ABC CD
document.body.style.['background-color'] = '#fff'
document.body.style.setProperty('background-color', '#fff')
document.body.style = 'background-color': #fff'
document.body.style.fontSize = '14px'
A. event.cancelBubble = true;
B. event.stopPropagation();
C. event.preventDefault();
D. return false;
答案
BCD ABD
var x = typeof x
var res = typeof typeof x;
console.log(x, res)
var arr = [];
console.log(typeof arr, Object.prototype.toString.call(arr));
// case 1
function showCase(value) {
switch(value) {
case 'A':
console.log('Case A');
break;
case 'B':
console.log('Case B');
break;
case undefined:
console.log('Case undefined');
break;
default:
console.log('Case default');
}
}
showCase(new String('A'));
// case 2
function showCase(value) {
switch(value) {
case 'A':
console.log('Case A');
break;
case 'B':
console.log('Case B');
break;
case undefined:
console.log('Case undefined');
break;
default:
console.log('Case default');
}
}
showCase(String('A'));
<html>
<body>
<p id="demo"></p>
<script type="text/javascript">
var x = 10;
var y = "10";
document.getElementById("demo").innerHTML = Boolean(x == y);
</script>
</body>
</html>
function funcA(x){
var temp = 4;
function funcB(y){
document.write( ++x + y + (temp--));
}
funcB(5);
}
funcA(6)
var varArr = function(i,j,str) {
return j == 0 ? str : varArr(i,--j,(str+= " " + i[j]));
}
var arr = new Array('apple','orange','peach','lime');
var str = varArr(arr,arr.length,"");
alert(str);
function greetingMaker(greeting) {
function addName(name) {
greeting = greeting.split(' ').reverse().join("-");
return greeting + " " + name;
}
return addName;
}
var daytimeGreeting = greetingMaker("Good Day to you");
alert(daytimeGreeting(name));
String.prototype.GetNum = function() {
var regEx = /[^\d]/g;
return this.replace(regEx, '');
};
var str = "a1b2c3";
str = str.GetNum();
alert(str);
function sum(a, b) {
return a + b;
}
sum(1, "2");
var str = "我非常喜欢编程";
str.length = 3;
console.log(str);
let number = 0;
console.log(number++);
console.log(++number);
console.log(number);
function nums(a, b) {
if (a > b)
console.log('a is bigger')
else
console.log('b is bigger')
return a + b
}
console.log(nums(4, 2))
console.log(nums(1, 2))
function side(arr) {
arr[0] = arr[2];
}
function func1(a, b, c = 3) {
c = 10;
side(arguments);
console.log(a + b + c);
}
function func2(a, b, c) {
c = 10;
side(arguments);
console.log(a + b + c);
}
func1(1, 1, 1);
func2(1, 1, 1);
var a = 3;
var b = new Number(3);
var c = 3;
console.log(a == b);
console.log(a === b);
console.log(b === c);
var a = [];
a.push(1, 2);
a.shift(3, 4);
a.concat([5, 6]);
a.splice(0, 1, 2);
var a = {}, b = '123', c = 123;
a[b] = 'b';
a[c] = 'c';
console.log(a[b]);
// example 2
var a = {}, b = Symbol('123'), c = Symbol('123');
a[b] = 'b';
a[c] = 'c';
console.log(a[b]);
// example 3
var a = {}, b = {key:'123'}, c = {key:'456'};
a[b] = 'b';
a[c] = 'c';
console.log(a[b]);
null == undefined
0.1 + 0.2 == 0.3
typeof NaN
typeof Function
typeof Object
typeof {}
'a' + 1
'a' - 1
Function instanceof Object
Object instanceof Function
var array = []
for(var i = 0; i < 3; i++) {
array.push(() => i)
}
var newArray = array.map(el => el())
console.log(newArray)
function a(m, n) {
var b = function (l) {
return l <= m ? l * b(l + 1) : 1;
}
return b(m - n + 1);
}
console.log(a(4, 2));
console.log(typeof undefined == typeof NULL);
console.log(typeof function () {} == typeof class {});
var a = 10
var b = {
age: 11
}
function fn(x,y) {
--y.age;
return --x;
}
fn(a,b)
var number = 4;
var numberFactorial = (function (number){
return (number === 0)? 1: number* factorial(number-1)
})(number)
console.log(numberFactorial)
var array = []
for(var i = 0; i < 3; i++) {
array.push(() => i)
}
var newArray = array.map(el => el())
console.log(newArray)
function addToList(item, list) {
return list.push(item)
}
const result = addToList("nowcoder", ["hello"])
console.log(result)
const first = () => { console.log('first'); return false; }
const second = () => { console.log('second'); return true; }
console.log( first() && second() );
console.log( second() || first() );
var s='12ab3cd', arr=s.split(/\d/);
console.log(arr[3],arr[4])
function getAge(...args) {
console.log(typeof args);
}
getAge(21);
var arr=[1,2,3];
arr.push(arr.shift())
console.log(arr[1],arr[2])
题目解析:this指向题目解析及扩展[3]
关于this还可以看看:可能是最好的 this 解析了...
var x = 1;
var obj = {
x: 3,
fun:function () {
var x = 5;
return this.x;
}
};
var fun = obj.fun;
console.log( obj.fun(), fun() );
var a = 5;
function test() {
a = 0;
alert(a);
alert(this.a);
var a;
alert(a);
}
new test();
function fun () {
return () => {
return () => {
return () => {
console.log(this.name)
}
}
}
}
var f = fun.call({name: 'foo'})
var t1 = f.call({name: 'bar'})()()
var t2 = f().call({name: 'baz'})()
var t3 = f()().call({name: 'qux'})
let obj1 = {
a: 1,
foo: () => {
console.log(this.a)
}
}
// log1
obj1.foo()
const obj2 = obj1.foo
// log2
obj2()
const Person = (name="wang",age=10) => {
this.name = name;
this.age = age;
return this.name +' is '+ this.age + 'years old'
}
let result = new Person('zhang',11)
console.log(result)
var person = {
age: 18,
getAge: function() {
return this.age;
}
};
var getAge = person.getAge
getAge()
var name = 'global';
var obj = {
name: 'local',
foo: function(){
this.name = 'foo';
}.bind(window)
};
var bar = new obj.foo();
setTimeout(function() {
console.log(window.name);
}, 0);
console.log(bar.name);
var bar3 = bar2 = bar;
bar2.name = 'foo2';
console.log(bar3.name);
var obj = {
name:"zhangsan",
sayName:function(){
console.info(this.name);
}
}
var wfunc = obj.sayName;
obj.sayName();
wfunc();
var name = "lisi";
obj.sayName();
wfunc();
var name='test'
var a = {
name: 'ass',
getName: function() {
return this.name;
}
}
var b = a.getName;
b();
const promiseA = Promise.resolve('a')
promiseA. then((res) => {
console.log(res)
}).then((res) => {
console.log(res)
})
const promiseB = Promise.resolve('b')
promiseB. then((res) => {
console.log(res)
})
promiseB. then((res) => {
console.log(res)
})
setTimeout(() => {
console.log(1)
}, 0)
const P = new Promise((resolve, reject) => {
console.log(2)
setTimeout(() => {
resolve()
console.log(3)
}, 0)
})
P.then(() => {
console.log(4)
})
console.log(5)
setTimeout(function(){
console.log(1);
}, 0)
new Promise(function(resolve){
console.log(2);
resolve();
console.log(3);
}).then(function(){
console.log(4);
})
console.log(5);
(async () => {
console.log(1);
setTimeout(() => {
console.log(2);
}, 0);
await new Promise((resolve, reject) => {
console.log(3);
}).then(() => {
console.log(4);
});
console.log(5);
})();
new Promise((resolve) => {
console.log('1')
resolve()
console.log('2')
}).then(() => {
console.log('3')
})
setTimeout(() => {
console.log('4')
})
console.log('5')
var p1 = new Promise(function(resolve, reject){
resolve("2")
})
setTimeout(function(){
console.log("1")
},10)
p1.then(function(value){
console.log(value)
})
setTimeout(function(){
console.log("3")
},0)
setTimeout(function() {
console.log('setTimeout');
}, 0);
Promise.resolve().then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
});
setTimeout(function() {
console.log(1)
},0)
new Promise(function executor(resolve){
console.log(2)
for (var i = 0; i<10000; i++) {
i - 9999 && resolve()
}
console.log(3)
}).then(function() {
console.log(4)
})
console.log(5)
<div class="outer">
<div class="inner"></div>
</div>
对应的js代码如下:
var outer = document.querySelector('.outer');
var inner = document.querySelector('.inner');
function onClick() {
console.log('click');
setTimeout(function() {
console.log('timeout');
}, 0);
Promise.resolve().then(function() {
console.log('promise');
});
outer.setAttribute('data-random', Math.random());
}
inner.addEventListener('click', onClick);
outer.addEventListener('click', onClick);
当点击class为inner的div块时,控制台依次输出结果是什么?10. 下面程序的输出结果是?
(async () => {
console.log(1);
setTimeout(() => {
console.log(2);
}, 0);
await new Promise((resolve, reject) => {
console.log(3);
}).then(() => {
console.log(4);
});
console.log(5);
})();
setTimeout(() => console.log('a'));
Promise.resolve().then(
() => console.log('b’);
).then(
() => Promise.resolve('c').then(
(data) => {
setTimeout(() => console.log('d'));
console.log('f');
return data;
}
)
).then(data => console.log(data));
console.log('one');
setTimeout(function() { console.log('two'); }, 0);
Promise.resolve()
.then(function() { console.log('three'); })
console.log('four');
setTimeout(function () {
console.log(C)
},0)
console.log('D')
new Promise(function(resolve){
console.log('E')
resolve()
console.log('F')
}).then(function() {
console.log('G')
})
console.log('H')
function log(msg, time) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(msg);
resolve();
}, time);
});
}
则下面三段代码输出的结果是:
// 第一段代码:
(async () => {
for (let i = 0; i < 5; i++) {
await log(i, 1000);
}
})();
// 第二段代码:
(async () => {
[ 1, 2, 3, 4 ].forEach(async (i) => {
await log(i, 1000);
});
})();
// 第三段代码:
(async () => {
for (const i of [ 1, 2, 3, 4 ]) {
await log(i, 1000);
}
})();
关于原型JS:看完这篇文章,彻底了解 “原型” & “this”
传送门: 原型与原型链题目解析[4]
function Fn1(name) {
if(name){
this.name = name;
}
}
Fn1.prototype.name="jack"
let a = new Fn1();
console.log('a:', a.name);
function Fn2(name) {
this.name = name;
}
Fn2.prototype.name="jack"
let b = new Fn2();
console.log('b:', b.name);
var Foo = (function() {
var x = 0;
function Foo() {}
Foo.prototype.increment = function() {
++x;
console.log(x);
};
return Foo;
})();
var a = new Foo();
a.increment();
a.increment();
var b = new Foo();
a.increment();
var name = 'Jay'
function Person(name){
this.name = name;
console.log(this.name)
}
var a = Person('Tom')
console.log(name)
console.log(a)
var b = new Person('Michael')
console.log(b)
class A{}
class B extends A{}
const a = new A()
const b = new B()
a.__proto__
b.__proto__
B. __proto__
B. prototype.__proto__
b.__proto__.__proto__
function test() {
getName = function() {
Promise.resolve().then(() => console.log(0));
console.log(1);
};
return this;
}
test.getName = function() {
setTimeout(() => console.log(2), 0);
console.log(3);
};
test.prototype.getName = function() {
console.log(4);
};
var getName = function() {
console.log(5);
};
function getName() {
console.log(6);
}
test.getName();
getName();
test().getName();
getName();
new test.getName();
new test().getName();
new new test().getName();
var tmp = {};
var A = function() {};
A. prototype = tmp;
var a = new A();
A. prototype = {};
var b = Object.create(tmp);
b.constructor = A. constructor;
console.log(a instanceof A);
console.log(b instanceof A);
function Foo(){}
Foo.prototype.z = 3;
var obj = new Foo();
console.info(obj.z)
obj.z = 10;
console.info(obj.z);
delete obj.z;
console.info(obj.z);
const Book = {
price: 32
}
const book = Object.create(Book);
book.type = 'Math';
delete book.price;
delete book.type;
console.log(book.price);
console.log(book.type);
function sayHello() {
console.log(name);
console.log(age);
var name = "Tom";
let age = 18;
}
sayHello();
for (var i = 0; i < 3; i++) {
setTimeout(_ => {
console.log(i)
})
}
for (let i = 0; i < 3; i++) {
setTimeout(_ => {
console.log(i)
})
}
console.log(a);
var a = 'a';
console.log(b);
let b = 'b';
var foo = "Hello";
(function(){
var bar = " World";
alert(foo + bar);
})();
alert(foo + bar);
var a = 10;
(function () {
console.log(a)
a = 5
console.log(window.a)
var a = 20;
console.log(a)
})()
const a = 10
function runFunction() {
const a = 20
console.log('inside', a)
}
runFunction()
console.log('outside', a)
"use strict"
var name = 'Jay'
var person = {
name: 'Wang',
pro: {
name: 'Michael',
getName: function () {
return this.name
}
}
}
console.log(person.pro.getName)
var people = person.pro.getName
console.log(people())
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script>
var elements = document.getElementsByTagName("li");
for (var i=0;i<elements.length;i++){
elements[i].onclick =function( ){
alert(i);
};
}
compute(10,100);
var compute = function(A,B) {
console.info(A * B) ;
};
function compute(A,B){
console.info(A + B);
}
function compute(A,B){
console.info((A + B)*2);
}
compute(2,10);
meili()
function meili() {
console.log("meili")
}
mogu()
var mogu = function() {
console.log("mogu")
}
// 片段1
check('first');
function check(ars){
console.log(ars);
}
// 片段2
check('second');
var check= function(ars){
console.log(ars);
}
const student = {name: 'ZhangSan'}
Object.defineProperty(student, 'age', {value: 22})
console.log(student)
console.log(Object.keys(student))
function * cb(x, y) {
for(let i = Math.ceil(x); i <= y; i++) {
yield i;
}
}
var a = cb(6, 9);
console.log(a.next());
console.log(a.next());
function fn(...args) {
console.log(typeof args);
}
fn(21);
Promise.reject(0)
.catch(e => e)
.catch(e => console.log(e))
class Person {
constructor (name) {
this.name = name;
}
greet () {
console.log(`Hi, my name is ${this.name}`);
}
greetDelay (time) {
setTimeout(() => {
console.log(`Hi, my name is ${this.name}`);
}, time);
}
}
function getPersonInfo (one, two, three) {
console.log(one)
console.log(two)
console.log(three)
}
const person = 'Lydia'
const age = 21
getPersonInfo `${person} is ${age} years old`
// module.js
export default () => "Hello world"
export const name = "nowcoder"
// index.js
import * as data from "./module"
console.log(data)
// a.js
let a = 1
let b = {}
setTimeout(() => {
a = 2
b.b = 2
}, 100)
module.exports = { a, b }
// b.js
const a = require('./a')
console.log(a.a)
console.log(a.b)
setTimeout(() => {
console.log(a.a)
console.log(a.b)
}, 500)
<div id="box1">
<div id="box2">
content
</div>
</div>
<script>
const $ = document.querySelector.bind(document);
const box1 = $('#box1');
const box2 = $('#box2');
box1.addEventListener('click', () =>{
console.log('box1 true');
}, true);
box1.addEventListener('click', () =>{
console.log('box1 false');
}, false);
box2.addEventListener('click', () =>{
console.log('box2 true');
}, true);
box2.addEventListener('click', () =>{
console.log('box2 false');
}, false);
</script>
$(function () {
function fn1( value ) {
alert( value );
}
function fn2( value ) {
fn1("A");
return false;
}
var callbacks = $.Callbacks();
callbacks.add( fn1 );
callbacks.fire( "B" );
callbacks.add( fn2 );
callbacks.fire( "C" );
})
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("<b>Hello World!</b>").______("p");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>在每个p元素的结尾添加内容</button>
</body>
</html>
<div id="box1">
<div id="box2">
content
</div>
</div>
<script>
const $ = document.querySelector.bind(document);
const box1 = $('#box1');
const box2 = $('#box2');
box1.addEventListener('click', () => {
console.log('box1 true');
}, true);
box1.addEventListener('click', () => {
console.log('box1 false');
}, false);
box2.addEventListener('click', () => {
console.log('box2 true');
}, true);
box2.addEventListener('click', () => {
console.log('box2 false');
}, false);
</script>
牛客网的45道JS能力评测题个人觉得是非常好的45道js基础检测题,基本就是对自己的JavaScript基础做一个比较全面的评估,包括if语句、循环体、基础操作符、setInterval、setTimeout、流程控制、常用数组方法及es6相关(解构、Map、Set、...等)。之前我已经做过一遍了,我记得以前牛客网不支持es6的写法,这两天花了点时间把所有题目又做了一遍,发现支持es6了。这次每个题目我都尽力用了不同的方法实现,建议各位看官收藏,需要的时候方便查看。当然如果你有更好更新颖的实现方法,欢迎评论区留言交流。
我也把常用的数组方法和字符串方法贴在这里,可以自测掌握程度
第一题比较简单,就直接上答案:
// 方法一
function indexOf(arr, item) {
if(Array.prototype.indexOf){// 判断浏览器是否支持indexOf方法
return arr.indexOf(item);
}else{
for(var i=0;i<arr.length;i++){
if(arr[i]===item){
return i;
}
}
}
return -1;
}
// 方法二
function indexOf(arr, item) {
if(Array.prototype.indexOf){// 判断浏览器是否支持indexOf方法
return arr.indexOf(item);
} else if (arr.indexOf(item) > 0) {
return arr.indexOf(item)
}else{
return -1
}
}
复制代码
这里顺便说一下Array.prototype.indexOf
indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
语法:
arr.indexOf(searchElement) //查找searchElement元素在数组中的第一个位置
arr.indexOf(searchElement[, fromIndex = 0]) //从fromIndex开始查找searchElement元素在数组中的第一个位置
复制代码
还有另外一个查找字符串的方法String.prototype.indexOf()
str.indexOf(searchValue[, fromIndex])
复制代码
具体可以看看MDN
方法一:普通的for循环拷贝+push
function append(arr, item) {
let resArr = []
for(let i = 0;i<arr.length;i++){
resArr.push(arr[i])
}
resArr.push(item)
return resArr
}
复制代码
方法二:使用concat将传入的数组或非数组值与原数组合并,组成一个新的数组并返回
function append(arr, item) {
return arr.concat(item);
}
复制代码
方法三:使用slice浅拷贝+push
function append(arr, item) {
let newArr = arr.slice(0); // slice(start, end)浅拷贝数组
newArr.push(item);
return newArr;
}
复制代码
方法四:...扩展运算符 如果不知道的,可以看看es6的相关知识
function append(arr, item) {
let resArr = [...arr,item]
return resArr
}
复制代码
这里需要注意理解题目,是直接操作原数组,所以不能出现newArr
方法一:普通for循环+splice
function removeWithoutCopy(arr, item) {
for(let i=arr.length;i>=0;i--){
if(arr[i]==item){
arr.splice(i,1);
}
}
return arr;
}
复制代码
方法二:方法一的另外一种写法
在这里要注意在删除掉一个元素时,要 i–,即删除这个元素后,其他元素位置往前移。
function removeWithoutCopy(arr, item) {
for(let i = 0; i< arr.length; i++) {
if(arr[i]===item) {
arr.splice(i,1);
i--;
}
}
return arr;
}
复制代码
把第3题稍微变一下,看下一题
方法一:filter过滤
function remove(arr, item) {
return arr.filter(res =>{
return res != item;
})
}
复制代码
方法二:for循环+push
function remove(arr, item) {
let resArr = []
for(let i = 0;i<arr.length;i++){
if(arr[i]!== item){
resArr.push(arr[i])
}
}
return resArr
}
复制代码
方法三:forEach+push(效率高于for循环)
function remove(arr, item) {
let resArr=[];
arr.forEach(v=>{
if(v!==item){
resArr.push(v);
}
})
return resArr;
}
复制代码
方法四:for循环+splice
function remove(arr,item){
let resArr= arr.slice(0);
for(let i=0;i<resArr.length;i++){
if(resArr[i] == item){
resArr.splice(i,1);
i--;
}
}
return resArr;
}
复制代码
方法一:普通for循环
function sum(arr) {
let res = 0
for(let i=0;i<=arr.length;i++){
res +=arr[i]
}
return res
}
复制代码
方法二:forEach循环
function sum(arr) {
let res = 0
arr.forEach((value,index,array)=>{
array[index] == value; //结果为true
res+=value;
});
return res;
};
复制代码
方法三:reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值,具体可以看看es6相关知识。
function sum(arr) {
return arr.reduce((pre,cur)=>{
return pre+cur;
})
}
复制代码
方法四:eval
eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。
function sum(arr) {
return eval(arr.join("+"));
}
复制代码
关注后私信回复前端“” 可以观看全部题目,还可以下载前端教程学习!
上就是毕业季了,很多同学都准备实习面试找工作了,今天来分享我在面试的毕业生的时候,会经常考察的16道JavaScript原理题,仅提供相应的核心原理和思路,具体细节大家可以收藏自己敲一遍研究理解。
一定要收藏自己练一遍!理解了才是自己的!
// 思路:将要改变this指向的方法挂到目标this上执行并返回
Function.prototype.mycall = function (context) {
if (typeof this !== 'function') {
throw new TypeError('not funciton')
}
context = context || window
context.fn = this
let arg = [...arguments].slice(1)
let result = context.fn(...arg)
delete context.fn
return result
}
// 思路:将要改变this指向的方法挂到目标this上执行并返回
Function.prototype.myapply = function (context) {
if (typeof this !== 'function') {
throw new TypeError('not funciton')
}
context = context || window
context.fn = this
let result
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
// 思路:类似call,但返回的是函数
Function.prototype.mybind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
let _this = this
let arg = [...arguments].slice(1)
return function F() {
// 处理函数使用new的情况
if (this instanceof F) {
return new _this(...arg, ...arguments)
} else {
return _this.apply(context, arg.concat(...arguments))
}
}
}
function myNew (fun) {
return function () {
// 创建一个新对象且将其隐式原型指向构造函数原型
let obj = {
__proto__ : fun.prototype
}
// 执行构造函数
fun.call(obj, ...arguments)
// 返回该对象
return obj
}
}
function person(name, age) {
this.name = name
this.age = age
}
let obj = myNew(person)('chen', 18)
// {name: "chen", age: 18}
// 思路:将传入的对象作为原型
function create(obj) {
function F() {}
F.prototype = obj
return new F()
}
// 思路:右边变量的原型存在于左边变量的原型链上
function instanceOf(left, right) {
let leftValue = left.__proto__
let rightValue = right.prototype
while (true) {
if (leftValue === null) {
return false
}
if (leftValue === rightValue) {
return true
}
leftValue = leftValue.__proto__
}
}
// 未添加异步处理等其他边界情况
// ①自动执行函数,②三个状态,③then
class Promise {
constructor (fn) {
// 三个状态
this.state = 'pending'
this.value = undefined
this.reason = undefined
let resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled'
this.value = value
}
}
let reject = value => {
if (this.state === 'pending') {
this.state = 'rejected'
this.reason = value
}
}
// 自动执行函数
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}
}
// then
then(onFulfilled, onRejected) {
switch (this.state) {
case 'fulfilled':
onFulfilled()
break
case 'rejected':
onRejected()
break
default:
}
}
}
// 1. ...实现
let copy1 = {...{x:1}}
// 2. Object.assign实现
let copy2 = Object.assign({}, {x:1})
// 可避免setInterval因执行时间导致的间隔执行时间不一致
setTimeout (function () {
// do something
setTimeout (arguments.callee, 500)
}, 500)
// 借用构造函数继承实例属性
function Child () {
Parent.call(this)
}
// 寄生继承原型属性
(function () {
let Super = function () {}
Super.prototype = Parent.prototype
Child.prototype = new Super()
})()
// 1. JOSN.stringify()/JSON.parse()
let obj = {a: 1, b: {x: 3}}
JSON.parse(JSON.stringify(obj))
// 2. 递归拷贝
function deepClone(obj) {
let copy = obj instanceof Array ? [] : {}
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
copy[i] = typeof obj[i] === 'object'?deepClone(obj[i]):obj[i]
}
}
return copy
}
// 组件通信,一个触发与监听的过程
class EventEmitter {
constructor () {
// 存储事件
this.events = this.events || new Map()
}
// 监听事件
addListener (type, fn) {
if (!this.events.get(type)) {
this.events.set(type, fn)
}
}
// 触发事件
emit (type) {
let handle = this.events.get(type)
handle.apply(this, [...arguments].slice(1))
}
}
// 测试
let emitter = new EventEmitter()
// 监听事件
emitter.addListener('ages', age => {
console.log(age)
})
// 触发事件
emitter.emit('ages', 18) // 18
let obj = {}
let input = document.getElementById('input')
let span = document.getElementById('span')
// 数据劫持
Object.defineProperty(obj, 'text', {
configurable: true,
enumerable: true,
get() {
console.log('获取数据了')
},
set(newVal) {
console.log('数据更新了')
input.value = newVal
span.innerHTML = newVal
}
})
// 输入监听
input.addEventListener('keyup', function(e) {
obj.text = e.target.value
})
// hash路由
class Route{
constructor(){
// 路由存储对象
this.routes = {}
// 当前hash
this.currentHash = ''
// 绑定this,避免监听时this指向改变
this.freshRoute = this.freshRoute.bind(this)
// 监听
window.addEventListener('load', this.freshRoute, false)
window.addEventListener('hashchange', this.freshRoute, false)
}
// 存储
storeRoute (path, cb) {
this.routes[path] = cb || function () {}
}
// 更新
freshRoute () {
this.currentHash = location.hash.slice(1) || '/'
this.routes[this.currentHash]()
}
}
// 思路:在规定时间内只触发一次
function throttle (fn, delay) {
// 利用闭包保存时间
let prev = Date.now()
return function () {
let context = this
let arg = arguments
let now = Date.now()
if (now - prev >= delay) {
fn.apply(context, arg)
prev = Date.now()
}
}
}
function fn () {
console.log('节流')
}
addEventListener('scroll', throttle(fn, 1000))
*请认真填写需求信息,我们会在24小时内与您取得联系。