javascript面试
1.以下代码将输出到控制台,为什么? (1. What will the code below output to the console and why?)
const person = { age: 20, name: 'Ben' };
const peopleArray = [person, person, person];
peopleArray[1].name = 'Joe';
console.log(peopleArray[0].name);
It will print Joe. The peopleArray has three elements, but all three elements are references to the same memory space, which is the person object. The following will create an array with three unique objects and outputs Ben.
它将打印Joe 。 peopleArray具有三个元素,但是所有三个元素都是对同一存储空间(即person对象)的引用。 下面将创建一个包含三个唯一对象的数组,并输出Ben 。
const person = { age: 20, name: 'Ben' };
const peopleArray = [{...person}, {...person}, {...person}];
peopleArray[1].name = 'Joe';
console.log(peopleArray[0].name);
2.以下代码将输出到控制台,为什么? (2. What will the code below output to the console and why?)
const carOne = {
color: 'blue',
status: {
running: true,
passengers: 4,
wiperFluid: 'empty'
},
age: 5,
miles: 50000,
value: '8000'
}const carTwo = {
color: 'green',
status: {
running: 'yes',
passengers: 2,
fuelTank: 'empty'
},
value: 9000
}const combinedCar = { ...carOne, ...carTwo } console.log(combinedCar);
It will print the below. Any property names common to both destructured objects will be overwritten by the second object.
它将打印以下内容。 两个解构对象共有的任何属性名称都将被第二个对象覆盖。
{
age: 5,
color: "green",
miles: 50000,
status: {
fuelTank: "empty",
passengers: 2,
running: "yes"
},
value: 9000
}
3.以下代码可以编译吗? 如果没有,为什么不呢? (3. Will the following code compile? If not, why not?)
const myName = 'Jim'; // Line 1 if(myName){ // Line 2
myName = 'Joe'; // Line 3
let myName = 'Jeff'; // Line 4
}
The code does not compile. Interestingly, Line 3 fails because let myName is not initialized to undefined (unlike var myName would have been). If Line 4 were removed, then Line 3 would fail due to the inability to override myName declared as a constant outside the code block. Constants cannot be changed.
该代码无法编译。 有趣的是,第3行失败,因为未将let myName初始化为undefined(与var myName不同)。 如果删除了第4行,则第3行将由于无法覆盖代码块外部声明为常量的myName而失败。 常量不能更改。
4.以下代码将输出到控制台,为什么? (4. What will the code below output to the console and why?)
const myMoney = {
quarters: 4,
dimes: 10,
nickels: 20,
pennies: 100
}for (const coin of myMoney){
console.log(`${coin}: ${myMoney[coin]}`);
}
The code will actually throw an error. for…of can only be used on objects that implement the @@iterator method. See this great article that covers four different ways to loop in JavaScript for more information. for…in would have printed off each key:value pair.
该代码实际上将引发错误。 for…of只能用于实现@@ iterator方法的对象。 有关更多信息,请参见这篇出色的文章 ,其中介绍了JavaScript循环的四种不同方式。 for…in将打印出每个key:value对。
5.编写一个箭头函数,通过以下函数调用,该函数可以成功打印“ hello world”: (5. Write an arrow function that successfully prints “hello world” given the following function call:)
console.log(concatenator('hello')('world'));
Here is one way to accomplish this:
这是完成此操作的一种方法:
const concatenator = (originalStr) => {
return (strTwo) => {
return `${originalStr} ${strTwo}`;
};
}
6.下面的代码将输出到控制台,为什么? (6. What will the code below output to the console and why?)
const myArr = [1,2,3];
const arrTwo = myArr.splice(0,4).slice(0,2);
arrTwo[0] = 9; console.log(arrTwo);
The code will output [9, 2]. Array.splice returns the original array, but Array.slice returns a new array, so changing arrTwo does not affect myArr.
代码将输出[9,2]。 Array.splice返回原始数组,但是Array.slice返回新数组,因此更改arrTwo不会影响myArr。
7.以下代码将输出到控制台,为什么? (7. What will the code below output to the console and why?)
const person1 = {
name: 'Willie',
address: {
city: 'Austin',
state: 'Texas'
}
}; const person2 = {...person1};
person2.name = 'Waylon';
person2.address.city = 'Fort Worth'; console.log(person1.address.city);
The output will be ‘Fort Worth’. Creating a new object using … is the equivalent of using Object.assign({}, object); and creates a shallow copy. person1 and person2 are not the same object, but both person1.address and person2.address are pointed to the same object in memory. See this article for a deeper explanation of shallow and deep copies in JavaScript.
输出将为“ Fort Worth”。 使用…创建新对象等效于使用Object.assign({},object);。 并创建一个浅表副本。 person1和person2不是同一对象,但是person1.address和person2.address都指向内存中的同一对象。 请参阅本文以更深入地解释JavaScript中的浅层副本和深层副本。
8.为修改原始字符串JavaScript String函数命名。 (8. Name a JavaScript String function that modifies the original string.)
Admittedly, this is a trick question. Strings are immutable in JavaScript, so there are no functions that modify the original string. There are some functions that extract or change portions of the original string and return it as a new string, leaving the original string unmodified.
诚然,这是一个技巧问题。 字符串在JavaScript中是不可变的,因此没有修改原始字符串的函数。 有一些函数可以提取或更改原始字符串的一部分,然后将其作为新字符串返回,而使原始字符串保持不变。
9.对还是错? 在下面的代码中,myColor初始化为布尔值true 。 (9. True or False? In the code below, myColor is initialized with a boolean value of true.)
const myColor = 'Purple' || 'Red';
This is false. The || operator does not actually return a boolean value, but rather the first truthy value it encounters. ‘Purple’ is a truthy value, so myColor is initialized to ‘Purple’.
这是错误的。 || 运算符实际上并不返回布尔值,而是它遇到的第一个真实值。 “ Purple”是真实值,因此myColor初始化为“ Purple”。
10.优化以下代码: (10. Optimize the following code:)
function truthy(x) {
if(5 === x){
return true;
}
else {
return false;
}
}console.log(truthy(6));
Here is a simple optimization:
这是一个简单的优化:
function truthy(x) {
return 5 === x;
} console.log(truthy(5));
Many devs write redundant lines of code, forgetting that ‘===’ itself returns a boolean.
许多开发人员编写了多余的代码行,却忘记了'==='本身会返回一个布尔值。
11.给出以下示例,在Object obj中设置enumerable:false的结果是什么? (11. Given the below example, what is the result of setting enumerable: false in Object obj?)
const obj = {};Object.defineProperty(
obj,
'key1',
{
enumerable: false,
configurable: true,
writable: true
}
);
Object obj will not be eligible to be enumerated over in a for…in loop.
对象obj将不适合在for…in循环中枚举。
12.下面的代码将输出到控制台,为什么? (12. What will the code below output to the console and why?)
const obj1 = {
a: 1,
b: 2
};const obj2 = {
b: 1,
c: 2
};const obj3 = {
c: 1,
d: 2
};Object.assign(obj1, obj2, obj3);
console.log(obj1);
The code will output {a: 1, b: 1, c: 1, d: 2}. Object.assign can take multiple sources, and later sources overwrite earlier sources.
代码将输出{a:1,b:1,c:1,d:2}。 Object.assign可以使用多个源,以后的源将覆盖以前的源。
13.以下代码将输出到控制台,为什么? (13. What will the code below output to the console and why?)
const obj1 = {
prop1: 'testA',
prop2: (
() => { return obj1.prop1; }
)()
} console.log(obj1.prop2);
It will throw an error saying ‘cannot access obj1 before initialization’. The code is attempting to immediately invoke the arrow function at prop2 while obj1 is still being initialized.
它将引发错误,提示“初始化前无法访问obj1”。 该代码试图在仍初始化obj1的同时立即调用prop2处的arrow函数。
14.考虑以下代码。 如何使用变量访问对象属性? (14. Consider the code below. How can object properties be accessed using a variable?)
const key = 'prop1';const obj1 = {
prop1: 1,
prop2: 2
} // console.log(???)
console.log(obj1[key]); will access prop1 on obj1. This is useful in many situations, such as when enumerating using a for…in loop.
console.log(obj1 [key]); 将访问obj1上的 prop1 。 这在许多情况下很有用,例如在使用for…in循环枚举时。
15.在JavaScript中使用严格模式有哪些限制? (15. What are some limitations placed by using Strict Mode in JavaScript?)
Take a look here for an exhaustive list. Most of the limitations revolve around variables. For example:
在这里查看详细列表。 大多数限制都围绕变量。 例如:
- all variables must be declared (the compiler won’t assume an undeclared variable is a global 必须声明所有变量(编译器不会假定未声明的变量是全局变量
- reserved words cannot be used as variable names 保留字不能用作变量名
- certain preceding values are not allowed, such as let badVal = /010; 不允许使用某些先前的值,例如let badVal = / 010;
- deleting undeletable properties is not allowed 不允许删除不可删除的属性
16.考虑下面的代码。 arr4和arrControl是否具有相同的值? (16. Consider the code below. Do arr4 and arrControl have the same values?)
const arr1 = 'jimmy'.split('');
const arr2 = arr1.reverse();
const arr3 = arr2.splice(0,5);
const arr4 = arr3.slice(0,5);const arrControl = 'jimmy'.split('').reverse().splice(0,5).slice(0,5);
They do indeed have the same values: [“y”, “m”, “m”, “i”, “j”]. It doesn’t matter whether the individual function returns are assigned to a const and then used, the result is the same either way.
它们确实具有相同的值: [“ y”,“ m”,“ m”,“ i”,“ j”] 。 各个函数返回的值是否分配给const然后使用都没有关系,两种方法的结果都是相同的。
17.考虑下面的代码。 第8行和第9行是否将相同的值记录到控制台? (17. Consider the code below. Do Line 8 and Line 9 log the same value to the console?)
const memoryFunction = (x) => {
const y = x;
return (z) => {
console.log(y * z);
}
}const innerMemoryFunction = memoryFunction(5); memoryFunction(6)(6); // Line 8
innerMemoryFunction(6)(6); // Line 9
Line 8 logs a value of 36. Line 9 initially logs a value of 30 and then throws an error. innerMemoryFunction is equal to (z) => { console.log(y*z); } has captured the closure value of y = 5 and uses that value when calculating.
第8行记录的值为36。第9行记录的初始值为30,然后引发错误。 innerMemoryFunction等于(z)=> {console.log(y * z); }已捕获y = 5的闭合值,并在计算时使用该值。
18.以下代码将输出到控制台,为什么? (18. What will the code below output to the console and why?)
console.log(1 && 0 === 1 || 0);
At first glance you may try to evaluate whether 1 && 0 is equivalent to 1 || 0. However, that’s not what the above code is doing. The code above is actually equivalent to the below:
乍一看,您可以尝试评估1 && 0是否等于1 ||。 0 。 但是,这不是上面的代码所做的。 上面的代码实际上等效于下面的代码:
console.log(1 && (0 === 1) || 0);
Which is the same as:
与以下内容相同:
console.log((1 && false) || 0);
The || operator returns the second value it checks when the first value is false, and since 1 && false is falsy, the above returns 0.
|| 当第一个值是false时,运算符返回它检查的第二个值,并且由于1 && false是falsy,因此上面的操作返回0 。
19.有两种方法可以仅使用一行代码将一个数组的元素推入另一个数组? (19. What are two ways to push elements of one array into another array using only one line of code?)
Here are two possible ways to do it.
这是两种可行的方法。
Option 1:
选项1:
const arr1 = [3,4,5];
[1,2, ...arr1];
This is simply just destructuring assignment.
这只是破坏分配。
Option 2:
选项2:
const arr = [1, 2];
arr.push.apply(arr, [3, 4, 5]);
This option is a little more complex. arr.push on line 2 simply calls the push function. The first param (arr) in the apply function actually tells the compiler which array to call the push on.
此选项稍微复杂一点。 第2行上的arr.push只是调用push函数。 apply函数中的第一个参数(arr)实际上告诉编译器哪个数组调用推入。
19.考虑下面的代码。 为什么即使我们在Car上没有定义toString也不抛出错误? (19. Consider the code below. Why doesn’t toString throw an error even though we have not defined it on Car?)
function Car (wheels){
this.wheels = wheels;
}const myCar = new Car(4);
myCar.toString()
toString is an instance method of Object. Car is of type Object, so it has all methods that Object has.
toString是Object的实例方法。 Car是Object类型的,因此它具有Object拥有的所有方法。
20.考虑下面的代码。 为什么第1行返回true而第2行返回false ? (20. Consider the code below. Why does Line 1 return true while Line 2 returns false?)
console.log(null == undefined == 0 == ''); // Line 1 console.log(null == undefined == 0 == '' == NaN); // Line 2
These evaluate as follows for Line 1:
对于第1行,这些评估如下:
So Line 1 returns true
所以第1行返回true
Line 2 then evaluates true == NaN which is false.
然后,第2行评估为true == NaN ,它为false。
21.函数可以作为参数传递吗? (21. Can functions be passed as parameters?)
Yes, and here is an example:
是的,这是一个示例:
const Person = (firstName, lastName, getUniqueID) => {
return {
firstName: firstName,
lastName: lastName,
getUniqueID: getUniqueID
}
}const person1 = Person(
'Jon',
'Jones',
() => {
return (person1.firstName + person1.lastName + Math.floor(Math.random() * 100))
}
);
This is an example where TypeScript would provide value. A developer looking at the Person constructor might guess that getUniqueID should be a function, but if the parameter had a type it would significantly reduce opportunity for confusion and bugs.
这是TypeScript提供价值的示例。 查看Person构造函数的开发人员可能会猜到getUniqueID应该是一个函数,但是如果参数具有类型,则它将大大减少混乱和错误的机会。
22.为什么开发人员应该使用“ ===”而不是“ ==”? (22. Why should developers use ‘===’ instead of ‘==’?)
‘===’ is stricter and checks if value and type are the same, ‘==’ only checks value and will do type coercion. But WHY do we want it stricter? Because developers need to write code that works as intended. Higher standards on code is a good thing and ensures developers don’t get sloppy.
'==='更严格,并检查值和类型是否相同,'=='仅检查值,并且将进行类型强制。 但是为什么我们要更严格? 因为开发人员需要编写按预期工作的代码。 较高的代码标准是一件好事,可确保开发人员不会草率。
23.对还是错? 尝试{}后需要一个catch块。 (23. True or False? A catch block is required after a try{}.)
This is false. However, either a catch block or a finally block is required after a try{}.
这是错误的。 但是,在try {}之后需要catch块或 finally块。
24.为什么console.log(〜8)输出-9? (24. Why does console.log(~8) output -9?)
~ is a bitwise operator that flips bits in the bit representation of a number. In JavaScript all bitwise operations are performed on 32-bit binary numbers.
〜是按位运算符,用于翻转数字的位表示形式中的位。 在JavaScript中,所有按位运算都是对32位二进制数执行的。
8 is represented as 00000000000000000000000000001000. The ~ operator flips this to 11111111111111111111111111110111, which is -9
8表示为00000000000000000000000000001000。〜运算符将其翻转为11111111111111111111111111110111,即-9
25.下面的代码将输出到控制台,为什么? (25. What will the code below output to the console and why?)
for(let i = 0; i < 10; i++){
if(i === 3){
return;
} console.log(i);
}
This will throw a syntax error. The return statement is not a valid way of ending a for block. If you want to end a loop, use break.
这将引发语法错误。 return语句不是结束for块的有效方法。 如果要结束循环,请使用break。
26.从对象中提取密钥的两种方法是什么? (26. What are two methods for extracting the keys from an Object?)
There are a handful of ways this could be accomplished, but two are below.
有几种方法可以实现,但是下面有两种。
Option 1:
选项1:
const obj1 = {
a: 'this',
b: 'that',
c: 'the other'
} console.log(Object.keys(obj1));
Object.keys(obj1) will extract the keys and return an array populated with a string representation of the keys.
Object.keys(obj1)将提取键,并返回一个填充有键的字符串表示形式的数组。
Option 2:
选项2:
const obj1 = {
a: 'this',
b: 'that',
c: 'the other'
}for(const key in obj1){
console.log(key);
}
Using for…in, each key is iterated over and a string representation of its value is set to the constant ‘key’ in the above example.
在上面的示例中 ,使用for…in迭代每个键,并将其值的字符串表示形式设置为常量“ key”。
27.下面的代码将输出到控制台,为什么? (27. What will the code below output to the console and why?)
let date = new Date(95, 3); console.log(date.toLocaleString('default'));
It prints “4/1/1995, 12:00:00 AM”. When only a year is provided, it maps to the 20th century. Also, January is month 0. Therefore, new Date(95, 3) creates a Date object set to April 1995.
打印“ 1995年4月1日,上午12:00:00” 。 如果只提供一年,则可以追溯到20世纪。 同样,一月是月份0。因此, 新的Date(95,3)创建一个Date对象,设置为1995年4月。
28.下面的代码将输出到控制台,为什么? (28. What will the code below output to the console and why?)
console.log(typeof (new String('hello')));
It will print ‘object’. We have created a string object, which is different than a string primitive in JavaScript.
它将打印“对象”。 我们创建了一个字符串对象,该对象与JavaScript中的字符串基元不同。
29.下面的代码将输出到控制台,为什么? (29. What will the code below output to the console and why?)
let x = 10;
setTimeout(
() => {console.log(x);},
1000
);
x = 5;
The output is 5. The timeout callback is not evaluated until 1000 milliseconds have passed, so x is never set to 10. It is only set once, to 5, and that is when the callback is evaluated.
输出为5 。 在经过1000毫秒之前不会评估超时回调,因此x永远不会设置为10。它只能设置一次,即设置为5,也就是评估回调时。
30.下面的代码会执行吗? (30. Will the below code execute?)
() => {console.log("problem?");}();
It will not. When attempting to immediately invoke an arrow function, don’t forget the needed parenthesis, like below:
它不会。 尝试立即调用箭头函数时,请不要忘记所需的括号,如下所示:
(() => {console.log("problem?");})();
31.下面的代码将输出到控制台,为什么? (31. What will the code below output to the console and why?)
console.log(typeof Object)
The output is “function”. While this may seem strange at first, Object is the name of the Object constructor function.
输出为“功能”。 乍一看这很奇怪,但Object是Object构造函数的名称。
32.可以运行以下代码吗? (32. Will the following code run?)
let hoister = 10;
const isItHoisted = function () {
console.log(hoister);
let hoister = 9;
};
isItHoisted();
The code will not run, but instead has a compile time error. let does not get hoisted, but the compiler doesn’t try to use the hoister variable specified outside the function.
该代码将不会运行,但是会出现编译时错误。 let不会被提升,但是编译器不会尝试使用函数外部指定的hoister变量。
33.累加器在Array.prototype.reduce()中做什么? (33. What does the accumulator do in Array.prototype.reduce()?)
The return value of the each iteration of the reducer function is assigned to the accumulator and remembered across each iteration of the array.
将reducer函数每次迭代的返回值分配给累加器,并在数组的每次迭代中记住该值。
34.用户在文本框中键入内容,并且onChange的触发频率比预期的高。 可以使用什么功能仅在用户键入结束时触发onChange? (34. A user is typing into a textbox, and the onChange is being fired more often than desired. What function could be used to only fire the onChange at the end of the user’s typing?)
debounce. The debounce function forces a function to wait a certain amount of time before being called or before being called again. Scroll events are another common use for debounce.
去弹跳 。 防反跳函数强制函数在调用之前或再次调用之前等待一定的时间。 滚动事件是反跳的另一种常见用法。
35.哪个函数告诉浏览器在下一次重绘之前调用指定函数来更新动画? (35. What function tells the browser to call a specified function to update an animation before the next repaint?)
window.requestAnimationFrame(). This is a useful function for making animations render more smoothly and more often.
window.requestAnimationFrame() 。 这是使动画更流畅,更频繁地渲染的有用功能。
36.如果div中存在一个按钮,并且按钮和div都具有单击侦听器,哪个首先处理事件? 他们俩都处理事件吗? (36. If a button exists inside a div, and both the button and div have click listeners, which one handles the event first? Do they both handle the event?)
The button click handler will be invoked, then the div click handler will be invoked. If you do not wish for the div to also have it’s click handler invoked, add event.stopPropagation() in the button click handler.
按钮单击处理程序将被调用,然后div单击处理程序将被调用。 如果您不希望div也调用它的单击处理程序,请在按钮单击处理程序中添加event.stopPropagation()。
37.下面的代码将输出到控制台,为什么? (37. What will the code below output to the console and why?)
console.log(isNaN(false));
This will output false. The value false will be coerced to 0, and NaN(0) will return false.
这将输出false 。 值false将强制为0 ,并且NaN(0)将返回false。
38.鉴于console.log(new Number(5)); 记录值5 ,下面的代码将输出什么到控制台,为什么? (38. Given that console.log(new Number(5)); logs the value 5, what will the code below output to the console and why?)
console.log(new Number(5) === 5);
This logs the value false. new Number(5) is an object, when it is logged to the console it’s toString() method is called so the value 5 is logged.
这将记录值false 。 new Number(5)是一个对象,当将其记录到控制台时,将调用toString()方法,因此将记录值5 。
39.编写一个确定字符是否为大写字母的函数。 (39. Write a function that determines if a character is an upper case letter.)
One possible solution:
一种可能的解决方案:
function isUpper(character){ const asciiVal = character.charCodeAt(0); return asciiVal >= 65 && asciiVal <= 90; }
40. ES6为数组添加了什么便利方法,以从类似于数组的可迭代对象创建数组? (40. What convenience method was added with ES6 to arrays to create an array from array-like and iterable objects?)
Array.from. Consider the following example:
Array.from 。 考虑以下示例:
const items = Array.from(document.querySelectorAll('li'));
41.下面的代码将输出到控制台,为什么? (41. What will the code below output to the console and why?)
console.log(
['Monday', 'Tuesday', 'Wednesday','Thursday', 'April', 'May', 'daylight']
.filter(
element => element.slice(-3) !== 'day'
)
);
This will output [“April”, “May”, “daylight”]. Adding parenthesis around the element param is not required because it is the only parameter passed in. Also, the return of the arrow function has an implied return when there are no brackets.
这将输出[“ April”,“ May”,“ daylight”] 。 不需要在元素参数周围添加括号,因为它是传入的唯一参数。此外,在没有括号的情况下,箭头函数的返回具有隐含的返回 。
42.评估下面的代码。 是否按预期打印或抛出错误? (42. Evaluate the code below. Does it print as intended or throw an error?)
const myFunc = ({a, b, c}) => {
console.log(`${a} ${b} ${c}`);
}myFunc(
{
a: 'one',
b: 'two',
c: 'three'
}
);
The code indeed prints one two three as intended. The parameters are passed in and destructured. Then interpolation is used to construct the string.
该代码确实按预期打印了一二三 。 参数被传入并被解构。 然后使用插值来构造字符串。
43.以下代码中的两个导入之间有什么区别? (43. What is the difference between the two imports in the below code?)
import Example from 'exampleLib';
import { Example } from 'exampleLib';
In the first import, exampleLib must have this syntax: ‘export default Example…..’. This is what is known as a default export from a package. In the second import, Example is a named export instead of the default export. The exampleLib package would need the following syntax: ‘export const Example….’ Functionally speaking, there’s not much difference other than syntax.
在第一次导入时,exampleLib必须具有以下语法:“导出默认示例.....”。 这就是所谓的从包默认导出。 在第二个导入中,Example是命名导出,而不是默认导出。 exampleLib软件包将需要以下语法:'export const Example…。' 从功能上讲,语法上没有什么区别。
44.下面的代码将输出什么,为什么? (44. What will the code below output and why?)
let switcheroo; switch('abc'){
case('abc'):
switcheroo = 'step 1';
case('def'):
switcheroo = 'step 2';
default:
switcheroo = 'step 3';
}console.log(switcheroo);
It will print step 3. Switch statements fall through all remaining steps after the first ‘true’ case they encounter, until the switch statement encounters a break. In the example, there was no break statement, so switcheroo was assigned ‘step 1’, then assign ‘step 2’, then assigned ‘step 3’.
它将打印步骤3 。 在遇到第一个“ true”情况之后,switch语句将执行所有其余步骤,直到switch语句遇到break为止。 在该示例中,没有break语句,因此将switcheroo分配为“步骤1”,然后分配为“步骤2”,然后分配为“步骤3”。
45.对还是错? event.preventDefault()停止事件传播。 (45. True or False? event.preventDefault() stops event propagation.)
The answer is False. preventDefault prevents the default action from being taken but does not prevent propogation.
答案是错误的。 preventDefault阻止采取默认操作,但不阻止传播。
46.分配默认参数值的语法是什么? (46. What is the syntax for assigning a default parameter value?)
It is as simple as parameter b in the below example:
在下面的示例中,它与参数b一样简单:
const myFunc = (a, b = 10) => {
console.log(a * b);
}myFunc(10); // prints 100
myFunc(10, 20); // prints 200
47.下面的代码将输出到控制台,为什么? (47. What will the code below output to the console and why?)
const obj1 = {
prop1: 'testA',
prop2: () => {
return obj1.prop3;
},
prop3: 'testB'
}console.log(obj1.prop2());
This will output testB. Other properties are accessible within an object’s function properties depending on when the function is invoked.
这将输出testB 。 根据调用函数的时间,可以在对象的函数属性中访问其他属性。
48.创建无法在对象中更改的属性的语法是什么? (48. What is the syntax for creating a property that can never be changed in an object?)
const obj= {};
Object.defineProperty(
obj,
'myProp',
{
value: 'Can't touch this',
writable: false
}
);
49.下面的代码将输出到控制台,为什么? (49. What will the code below output to the console and why?)
const myArray = ['thing 1', 'thing 2', 'thing 3'];
myArray.thing4 = 'not a thing';for(const element in myArray){
console.log(myArray[element]);
}
The code will print “thing 1”, “thing 2”, “thing 3”, and “not a thing”. It does not fail, but the results may be unexpected. for…in loops through the keys of an object, and in this case thing4 has been added to the myArray object.
该代码将打印“事物1”,“事物2”,“事物3”和“不是事物”。 它不会失败,但是结果可能是意外的。 for…in在对象的键之间循环,在这种情况下,thing4已添加到myArray对象中。
50.下面代码的第5行向控制台输出什么? (50. What does Line 5 of the code below output to the console?)
const yourString = '123';
let iterator = yourString[Symbol.iterator](); console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next()); // Line 5
console.log(iterator.next()); // Line 6
Line 5 prints the following:
第5行显示以下内容:
{ done: false, value: "3" }
done: true is not printed until Line 6.
完成:直到第6行才打印true 。
奖励:semver语法中的“〜”和“ ^”有什么区别,例如npm package.json文件中使用的语法? (Bonus: What is the difference in the ‘~’ and the ‘^’ in the semver syntax, such as that used in npm package.json file?)
Semver syntax goes as follows: major.minor.patch.
Semver语法如下:major.minor.patch。
‘~’, for example “lodash”: “~1.2.0”, will only update the patch version.
“〜”,例如“ lodash”:“〜1.2.0”,将仅更新补丁程序版本。
‘^’, for example “lodash”: “^.2.0”, will update the minor and patch version.
'^',例如“ lodash”:“ ^。2.0”,将更新次要版本和修补程序版本。
I believe every developer should create a portfolio to showcase their skills. I chose Medium as my platform and it has let me focus on code, grow my skill set and audience, and even earn some income. Not convinced? Here’s why you should build your dev portfolio on Medium (and how to get paid to do it).
我相信每个开发人员都应该创建一个投资组合来展示自己的技能。 我选择Medium作为平台,它使我能够专注于代码,提高技能和受众,甚至获得一些收入。 不服气吗? 这就是为什么您应该在Medium上构建开发项目组合的原因 (以及如何获得报酬)。
翻译自: https://medium.com/the-clever-dev/50-difficult-javascript-interview-questions-88e6e92367e7
javascript面试