When the user moves the mouse pointer over an element, the Tooltip component appears as a little pop-up box. The Popover component is a pop-up box that emerges when the user clicks on an element. The popover may hold a lot more information.
In Bootstrap, Jumbotron is used to highlight contents. It enlarges the headline and provides a margin for the landing page's content. In order to implement Jumbotron in Bootstrap, create a container div with the .jumbotron class.
It's an auto-updating nav component that allows you to grab sections of the page based on where you're scrolling. Based on the scroll position, the .active class will update from one nav item to the next.
You may collapse any element with Bootstrap collapsing elements without creating any JavaScript code or accordion markup. To automatically delegate control of a collapsible element in bootstrap, add data-toggle= "collapse" to the controller element along with a data-target or href. You may also do the same thing with .collapse (options), .collapse (‘show'), or .collapse (‘hide').
The affix plugin allows you to affix a to a particular location on the page. You may also use this plugin to turn on and off the pinning. Social icons are a good example of this. They'll start in one position, but when the page reaches a certain point, the will be frozen in place and will no longer scroll with the rest of the page.
One of the most intriguing properties of bootstrap is column ordering. The columns can be readily written in a specific order by utilizing relevant functions. You might alternatively put them in a different column. Use the push and pull column classes to easily rearrange or rearrange the order of the columns. These classes are used in conjunction with the .col-xs-#, .col-sm-#, .col-md-#, and .col-lg-# Bootstrap grid classes.
.col-xs-push-# and .col-xs-pull-# are the push and pull classes for the Bootstrap grid. This also works well for sm, md, and lg. The pull class moves columns to the left, whereas the push class moves them to the right.
Badges are used to supplement any content with additional information. To make rectangular badges, use the .badge class with a contextual class (like .badge-secondary) within elements. It's worth noting that badges scale to fit the parent element's size (if any).
Pagination is how Bootstrap handles an unordered list. The following classes are provided by bootstrap to manage pagination: 分页是Bootstrap处理无序列表的方式。Bootstrap提供了以下类来管理分页:
.pagination : This class is required to enable pagination on your page.
.pagination :此类在页面中启用分页功能时是必需的。
.disabled, .active : Use .disabled for unclickable links and .active to indicate the current page when customising links.
Glyphicons are icon fonts that you can use on your website. Their developer has made them freely available for Bootstrap projects.
字形图标是可以用在网站上的图标字体。其开发者已将它们免费提供给 Bootstrap 项目使用。
To utilize the icons, simply copy and paste the following code anywhere in your code. To ensure adequate padding, leave a space between the icon and the text.
Note : Bootstrap 4 lacks an icon library of its own (Glyphicons from Bootstrap 3 are not supported in BS4). 注意:Bootstrap 4 没有自己的图标库(Bootstrap 3 中的字形图标在 BS4 中不受支持)。
The Bootstrap well is simply a container that makes the content appear sunken. It can also produce an inset effect on the webpage. With the aid of and class, a developer may create a well and also wrap the content in the well. The content will be displayed according to your preferences.
Bootstrap well 只是一个使内容看起来凹陷的容器。它还可以在网页上产生嵌入效果。借助相关类和标签,开发者可以创建 well,并将内容包裹在 well 中。内容将按照你的偏好显示。
CSS Grid Layout is a two-dimensional system, meaning it can handle both columns and rows. Grid layout is intended for larger-scale layouts which aren’t linear in design.
Flexbox is largely a one-dimensional system (either in a column or a row). Flexbox layout is most appropriate to the components of an application.
Absolute: To place an element exactly where you want to place it. absolute position is actually set relative to the element's parent. if no parent is available then the relative place to the page itself (it will default all the way back up to the element).
Relative: "Relative to itself". Setting position: relative; on an element and no other positioning attributes, it will no effect on its positioning. It allows the use of z-index on the element and it limits the scope of absolutely positioned child elements. Any child element will be absolutely positioned within that block.
Fixed: The element is positioned relative to the viewport or the browser window itself. viewport doesn't change if you scroll and hence the fixed element will stay right in the same position.
Static: Static default for every single page element. The only reason you would ever set an element to position: static is to forcefully remove some positioning that got applied to an element outside of your control.
Sticky: Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.
Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document.
重排是 Web 浏览器重新计算文档中元素位置和几何形状的过程,目的是重新渲染文档的部分或全部内容。
Reflow occurs when: - Insert, remove or update an element in the DOM.
重排发生在以下情况:- 在 DOM 中插入、删除或更新元素。
Modify content on the page, e.g. the text in an input box.
Move a DOM element.
Animate a DOM element.
Take measurements of an element such as offsetHeight or getComputedStyle.
The box-sizing CSS property sets how the total width and height of an element are calculated. - Content-box: The default width and height values apply to the element's content only. The padding and border are added to the outside of the box.
Padding-box: Width and height values apply to the element's content and its padding. The border is added to the outside of the box. Currently, only Firefox supports the padding-box value.
Border-box: Width and height values apply to the content, padding, and border.
1279. How to center align a div inside another div?
All → It’s the default property. Used for all media-type devices. 2. Screen → Used for computer screen, mobile screen. 3. Print → Used for printers. 4. Speech → Used for screen readers.
CSS Grid Layout is the most powerful layout system available in CSS. It is said to be a 2-dimensional system, meaning it can handle both columns and rows, unlike flexbox which is largely a 1-dimensional system.
Using display property(display: none). It’s not available for screen readers. The element will not exist in the DOM if display: none is used.
Using visibility property(visibility: hidden), will take up the space of the element. It will be available to screen reader users. The element will actually be present in the DOM, but not shown on the screen.
Using position property (position: absolute). Make it available outside the screen.
The :root selector allows you to target the highest-level “parent” element in the DOM, or document tree. It is defined in the CSS Selectors Level 3 specification.
Accessibility refers to how software or hardware combinations are designed to make a system accessible to persons with disabilities, such as visual impairment, hearing loss, or limited dexterity.
无障碍性指的是软件或硬件组合如何被设计为让残障人士(如视力障碍、听力损失或行动不便)能够使用系统。
For example, a website developed with accessibility in mind might have text-to-speech capabilities. In the USA public websites have to have accessible compliance. It’s defined in 508 compliance. It gives the guidelines and best practices for all website users that should be met with key areas of accessibility.
The CSS3 calc() function allows us to perform mathematical operations on property values. Instead of declaring, for example, static pixel values for an element's width, we can use calc() to specify that the width is the result of the addition of two or more numeric values.
Custom properties (sometimes referred to as CSS variables or cascading variables) are defined by users that contain specific values to be reused throughout a document. The value is set using -- notion. And the values are accessed using the var() function.
A process of determining which CSS rule will be applied to an element. It actually determines which rules will take precedence. Inline style usually wins then ID then the class value (or pseudo-class or attribute selector), the universal selector (*) has no specificity. ID selectors have a higher specificity than attribute selectors.
Progressive rendering is the name given to techniques used to improve the performance of a webpage (in particular, improve perceived load time) to render content for display as quickly as possible.
渐进式渲染是用来改善网页性能(尤其是提高感知加载时间)的技术名称,以便尽快渲染内容进行显示。
We can implement the progressive rendering of the page by loading the lazy loading of the images. We can use Intersection Observer API to lazy load the image. The API makes it simple to detect when an element enters the viewport and take an action when it does. Once the image enters the viewport, we will start loading the images.
Translate() does not cause the browser to trigger repaint and layout and instead only acts on the compositor. The absolute position triggers the repaint or DOM reflow. So, translate() gives better performance.
Different ways to fix browser-specific issues. - We can write browser-specific styles separately in different sheets and load that only when the specific browser is used. This makes use of the server-side rendering technique.
We can use auto-prefix for automatically adding vendor prefixes in the code.
We can also use normalize.css or reset CSS techniques. There are some ways for avoiding browser compatibility issues too. They are as follows: - Validate HTML and CSS: We know that the code will be read, interpreted and handled differently by different browsers. We need to validate our HTML and CSS files for the missing closing tags, or missing semicolons in the syntaxes because there are chances that the old browsers will throw errors while rendering the code. We can avoid those errors by:
也有一些避免浏览器兼容性问题的方法。它们如下:- 验证 HTML 和 CSS:我们知道代码会被不同的浏览器以不同的方式读取、解释和处理。我们需要验证 HTML 和 CSS 文件中的缺失闭合标签或语法中缺失的分号,因为旧浏览器在渲染代码时可能会抛出错误。我们可以通过以下方式避免这些错误: Maintaining well-aligned code that helps in easy readability. Inserting comments at necessary places. Make use of validation tools like Jigsaw CSS validator, W3C HTML Validators to identify syntax issues in the code. - Maintain Cross-Browser Compatibility in the Layouts: Cross-Browser compatibility is a must while developing web applications. We expect our application to be responsive across all devices, browsers and platforms. Some of the effects of layout incompatibilities are unresponsiveness of the layouts in mobile devices, the difference in layout rendering between modern and old browsers, etc. These incompatibilities can be avoided by using: 维护排列良好的代码,有助于轻松阅读。在必要位置插入注释。使用 Jigsaw CSS 验证器、W3C HTML 验证器等验证工具来识别代码中的语法问题。- 在布局中保持跨浏览器兼容性:在开发 Web 应用程序时,跨浏览器兼容性是必须的。我们希望应用程序在所有设备、浏览器和平台上都能响应式工作。布局不兼容的一些影响包括布局在移动设备上不响应、现代和旧浏览器之间布局渲染的差异等。这些不兼容可以通过使用以下方式避免: CSS Multi-Column layouts - For maintaining proper layouts w.r.t columns and containers. HTML viewport metatag – For ensuring content is properly spanned across mobile devices. CSS Flexbox and Grids - To layout child elements depending on the content and available space. CSS resets stylesheets - For reducing browser inconsistencies in default line heights, font sizes, margins etc. - Check JavaScript Library issues: Ensure the libraries are used judiciously and the ones used are supported by the browsers. CSS 多列布局 - 用于保持相对于列和容器的正确布局。HTML 视口元标签 - 用于确保内容在移动设备上正确扩展。CSS Flexbox 和 Grid - 用于根据内容和可用空间布局子元素。CSS 重置样式表 - 用于减少浏览器在默认行高、字体大小、边距等方面的不一致。- 检查 JavaScript 库问题:确保合理使用库,并且所使用的库得到浏览器的支持。
Check DOCTYPE tag keyword: The DOCTYPE keyword is meant for defining rules of what needs to be used in the code. Older browser versions check for DOCTYPE tag at the beginning and if not found, the application rendering won't be proper.
Test on real devices: Although applications can be tested on virtual environments, it would be more beneficial if the testing is carried out on real devices and platforms. We can use tools like Testsigma for this purpose that enables us to test in real devices parallelly. Conclusion
结论
CSS plays the most important role in the field of web development. This is because CSS helps in achieving beautiful, responsive or adaptive websites depending on the business requirements. CSS helps in building lighter and flexible layouts that help in loading pages faster and making the content visually appealing. CSS is continuously evolving and is becoming more powerful thereby making it the most sought-after technology by various companies to develop websites. In this article, we have seen the most commonly asked interview questions in CSS, more particularly CSS3.
The overflow property in CSS is used for specifying whether the content has to be clipped or the scrollbars have to be added to the content area when the content size exceeds the specified container size where the content is enclosed. If the value of overflow is hidden, the content gets clipped post the size of the container thereby making the content invisible. For example,
div { width: 150px; width: 150px; height: 50px; height: 50px; overflow: hidden; overflow: hidden; } If the content of the div is very large and exceeds the height of 50px, the content gets clipped post 50px and the rest of the content is not made visible. 如果 div 的内容非常大并超过 50px 的高度,内容将在 50px 后被裁剪,剩余部分不会显示出来。
1297. How will you align content inside the p tag at the exact center inside the div?
We can add the text-align: center property inside the parent div for aligning the contents horizontally. But it will not align the contents vertically. We can align the content vertically by making the parent element have relative positioning and the child element have absolute positioning. The child element should have the values of top, bottom, right, left as 0 to center it in the middle vertically. Then we need to set the margin as auto. It is assumed that both the child and mother elements will have height and width values.
Consider we have a div element of height and width taking 20% of the screen size, and we have a paragraph element taking the height of 1.2em and width of 20%. If we want to align the paragraph element at the center (vertically and horizontally), we write the following styles:
Margin property using which we can create space around the elements. We can also create space for borders defined at the exteriors. We have the following properties for defining the margin: - margin-top
margin-leftmargin property by itself has the values as:
auto – The browser auto-calculates the margin while we use this.
length – The value of this property can be in px, pt, cm, em etc. The values can be positive or negative.
% – We can also give percentage value as margin to the element.
inherit – Using this property, the margin properties can be inherited from the parent elements. The padding property is used for generating the space around the element’s content and inside any known border. The padding also has sub-properties like: - padding-top
padding-left It is to be noted that the padding does not allow negative values.
需要注意的是,padding不允许负值。
From the below image, we can see that the Margin is the outermost entity of the CSS Box Model that lies outside of the borders whereas the padding lies within the borders.
We can use the concept of CSS counters. This lets us adjust the appearance of the content based on the location in a document. While using this, we need to first initialize the value of the counter-reset property which is 0 by default. The same property is also used for changing the value to any number that we need. Post initialization, the counter’s value can be incremented or decremented by using the counter-increment property. The name of the counter cannot be CSS keywords like “none”, “initial”, “inherit” etc. If the CSS keywords are used, then the declaration would be ignored.
body { counter-reset: header; / define counter named 'header' whose initial value is 0 by default / counter-reset: header; / 定义一个名为'header'的计数器,其初始值默认为0 / }
h2::before {
h2::before { counter-increment: header; / The value of header counter by 1./ counter-increment: header; / 将header计数器的值递增1。/ content: "Header " counter(header) ": "; / To display word Header and the value of the counter with colon before it./ content: "Header " counter(header) ": "; / 用于显示单词“Header”和计数器值,并在其前加上冒号。/ } Here, we are trying to achieve auto count increment and display feature for the h2 tag. Wherever we use h2 tag, the content will be prefixed by "Header 1 : " , "Header 2 : ", "Header 3 : " etc. 在这里,我们试图为h2标签实现自动计数递增和显示功能。无论我们在哪里使用h2标签,内容都将以“Header 1 : ”、“Header 2 : ”、“Header 3 : ”等作为前缀。
1300. How is the nth-child() different from nth of type selectors?
Both are pseudo-classes (Pseudo-classes are those keywords that specifies the special state of the selected element). The nth-child() pseudo-class is used for matching elements based on the number that represents the position of an element based on the siblings. The number is used to match an element on the basis of the element’s position amongst its siblings.
For example, in the below piece of code, if we give nth-child(4) for the example class, then the 4th child of the example class is selected irrespective of the element type. Here, the fourth child of the example class is the div element. The element is selected and a background of black is added to it.
The nth-of-type() pseudo-class is similar to the nth-child but it helps in matching the selector based on a number that represents the position of the element within the elements that are the siblings of its same type. The number can also be given as a function or give keywords like odd or even. nth-of-type()伪类类似于nth-child,但它有助于根据一个数字来匹配选择器,该数字表示元素在与其同类型的兄弟元素中的位置。该数字也可以作为函数给出,或给出关键词如odd或even。
For example, in the below piece of code, if we give p:nth-of-type(even) for the example class, then all the even paragraph tags are selected within the example class and the style of background black is applied to them. The selected elements are marked in comments in the below code:
CSS sprites are used for combining multiple images in a single larger image. They are commonly used for representing icons that are used in the user interfaces. The main advantages of using sprites are: - It reduces the number of HTTP requests to get data of multiple images as they are acquired only by sending a single request.
It helps in downloading assets in advance that help display icons or images upon hover or other pseudo-states.
When there are multiple images, the browser makes separate calls to get the image for each of them. Using sprites, the images are combined in one and we can just call for that image using one call. Consider an example where our application requires 3 images as shown below (Without Sprites Section). If we are trying to load the images independently, we require 3 different HTTP Requests to get the data. But if we have CSS Sprites where all 3 images are combines into 1 separated by some spaces, then we require only 1 HTTP Request.
We can access each image from the sprite by accessing the positioning properties as shown in the below code:
我们可以通过访问如下代码中所示的定位属性来从Sprite中访问每个图像:
<!DOCTYPE html>
<!DOCTYPE html>
In the above code, we are trying to access each element - house, previous and next icon - from the sprite file by using the left, width properties. The image is displayed in the img section by means of the background property. Do note that the source of the image (src attribute of the img tag) is just one file which is the spriteFile.gif and depending on the rules specified in the id selectors, the images are loaded accordingly. 在上面的代码中,我们尝试通过使用 left 和 width 属性从精灵文件中访问每个元素——主页、上一个和下一个图标。图像通过 background 属性显示在 img 部分中。请注意,图像的来源(img 标签的 src 属性)只是一个文件,即 spriteFile.gif,并且根据 id 选择器中指定的规则,相应地加载图像。
Tweening is the process of filling the gaps between the key sequences, i.e between the keyframes that are already created. Keyframes are those frames that represent start and end point of animation action. Tweening involves generating intermediate keyframes between two images that give the impression that the first one has evolved smoothly to the second image. For this purpose, we use properties like transforms - matrix, translate, scale, rotate etc.
@keyframes slidethrough { from { from { margin-left: 100%; margin-left: 100%; width: 300%; width: 300%; }
to {
to { margin-left: 0%; margin-left: 0%; width: 100%; width: 100%; } } Here, the paragraph element specifies that the animation process should take 2 seconds for execution from start to the finish. This is done by using the animation-duration property. The animation-name of the @keyframes is defined by using the property animation-name . The intermediate keyframes are defined by using @keyframes rule. In the example, we have just 2 keyframes. The first keyframe starts at 0% and runs till the left margin of 100% which is the rightmost edge of the containing element. The second keyframe starts at 100% where the left margin is set as 0% and the width to be set as 100% which results in finishing the animation flush against the left edge of the container area. 这里,段落元素指定动画过程从开始到结束应耗时2秒。这是通过使用animation-duration属性实现的。@keyframes的动画名称通过使用animation-name属性定义。中间关键帧通过使用@keyframes规则定义。在示例中,我们只有2个关键帧。第一个关键帧从0%开始,一直运行到左外边距为100%,即包含元素的最右边缘。第二个关键帧从100%开始,此时左外边距设置为0%,宽度设置为100%,这导致动画在容器区域的左边缘平整结束。
1303. Why do we need to use clear property along with floats in CSS?
The clear property along with floats is used for specifying which side of floating elements is not supposed to float. An element having clear property ensures that the element does not move up adjacent to the float. But the element will be moved down past the float.
Let us understand this with the help of an example. We know that the floated objects do not add to the height of the objects where they reside. Consider we have a div element with class “floated_div” within another div element with id “main_div”.
The result of this code would be as shown below. We see that the squares that are expected to be within dev are not within the main parent div. How do we fix this? 这段代码的结果如下所示。我们可以看到,本应位于 dev 内的方块并没有位于主父级 div 内。我们如何解决这个问题?
We can do it just by adding
我们只需添加 line at the end of the last floated element so that the floated elements are fit in properly within the main div container. 在最后一个浮动元素末尾添加一行,这样浮动元素就能正确地适配到主 div 容器内。
Absolute positioning is a very powerful positioning mechanism that allows users to place any element wherever they want in an exact location. The CSS properties right, left, top, bottom and define the exact locations where you need to place the element. In absolute positioning, the following points need to be considered: - The element to which the absolute positioning is applied is removed from the normal workflow of the HTML document.The HTML layout does not create any space for that element in its page layout.
The element is positioned relative to the closest positioned ancestor. If no such ancestor is present, then the element is placed relative to the initial container block.
The final position of the element is determined based on values provided to the top, right, left, bottom.
1305. What is the object-fit property in CSS? Explain all its values.
The object-fit property controls how replaced elements like and resize inside their container.
object-fit属性控制替换元素(如和)如何在容器内调整大小。
When you set a fixed width and height on an image, the image may stretch or distort. object-fit defines how the image should scale to fit that container.
.image { width: 300px; width: 300px; height: 200px; height: 200px; object-fit: cover; object-fit: cover; } The possible values are: 可能的值有:
fill: This is the default value. The content stretches to fill the container completely. The aspect ratio is not preserved, so distortion can happen.
contain: The content scales to fit entirely inside the container while keeping its aspect ratio. No cropping occurs, but empty space (letterboxing) may appear on the sides or top/bottom.
cover: The content scales to completely cover the container while keeping its aspect ratio. Some parts may be cropped. This is commonly used for hero images and profile pictures.
none: The content keeps its original size. It does not resize. If it is larger than the container, it overflows.
scale-down: The browser compares none and contain and uses whichever results in a smaller image.
There is also a companion property called object-position. It controls how the image is aligned inside the container. The default is:
还有一个配套属性叫做object-position。它控制图像在容器内的对齐方式。默认值为: object-position: 50% 50%; object-position: 50% 50%; This means the image is centered. 这意味着图像是居中的。
Example of a circular avatar without distortion:
无扭曲的圆形头像示例:
.avatar {
.avatar { width: 100px; width: 100px; height: 100px; height: 100px; object-fit: cover; object-fit: cover; border-radius: 50%; border-radius: 50%; } The image fills the circle without stretching. 图片填满圆形而不变形。
1306. What are the :is(), :where(), and :not() pseudo-class functions in CSS?
h1, h2, h3 { color: blue; color: blue; } The important detail is specificity. The specificity of :is() equals the most specific selector inside it. 重要的细节是特异性。:is() 的特异性等于其内部最具体的选择器。
Example:
示例:
:is(.card, #main) {
:is(.card, #main) { padding: 20px; padding: 20px; } Since #main has ID specificity, the whole rule takes that specificity. 由于 #main 具有 ID 特异性,整个规则就采用该特异性。
:is() is also forgiving. If one selector inside it is invalid, the browser ignores only that part instead of discarding the entire rule.
:is() 也是宽容的。如果其中某个选择器无效,浏览器只忽略部分内容,而不是丢弃整个规则。
:where() - :where() works the same way as :is(), but it always has zero specificity.
Example:
示例: :where(.card, .panel) .title { :where(.card, .panel) .title { font-size: 18px; font-size: 18px; } The specificity here comes only from .title, not from .card or .panel. 这里的具体性仅来自 .title,而非 .card 或 .panel。
This makes :where() useful for writing base styles that should be easy to override later.
这使得 :where() 适合编写日后易于覆盖的基础样式。
:not() - :not() selects elements that do not match the given selector.
Example:
示例: button:not(.active) { button:not(.active) { opacity: 0.5; opacity: 0.5; } This selects all buttons that do not have the class active. 这会选中所有不具有 active 类的按钮。
In modern CSS, :not() can accept multiple selectors:
在现代 CSS 中,:not() 可以接受多个选择器:
:not(.a, .b)
:not(.a, .b) These pseudo-class functions can also be combined: 这些伪类函数也可以组合使用:
article :is(h1, h2):not(.subtitle) {
article :is(h1, h2):not(.subtitle) { margin-bottom: 10px; margin-bottom: 10px; } This selects h1 or h2 inside an article, except those with class subtitle. 这会选中文章内的 h1 或 h2,但不包括具有 subtitle 类的元素。
These selectors make stylesheets shorter and easier to maintain, especially in large projects.
这些选择器使样式表更简洁、更易维护,尤其在大型项目中。
1307. What is the CSS filter property? What effects can you achieve with it?
The filter property applies graphical effects to an element, similar to image editing tools.
filter 属性为元素应用图形效果,类似于图像编辑工具。
Example:
示例:
.image {
.image { filter: grayscale(100%); filter: grayscale(100%); } This removes color from the image. 这会从图像中移除颜色。
Common filter functions include: - blur(5px) - Applies blur effect.
常见的滤镜函数包括:- blur(5px) - 应用模糊效果。
brightness(1.5) - Adjusts brightness.
contrast(200%) - Changes contrast level.
grayscale(100%) - Removes color.
hue-rotate(90deg) - Shifts color tone.
invert(100%) - Inverts colors.
opacity(50%) - Adjusts transparency.
saturate(200%) - Increases color intensity.
sepia(100%) - Adds warm brown tone.
drop-shadow(4px 4px 10px rgba(0,0,0,0.5)) - Adds shadow following the element’s shape. Multiple filters can be combined:
多个滤镜可以组合使用:
.image {
.image { filter: grayscale(100%) blur(2px); filter: grayscale(100%) blur(2px); } There is also backdrop-filter, which applies effects to the content behind an element. 还有backdrop-filter,它会对元素背后的内容应用效果。
Example:
示例:
.glass {
.glass { backdrop-filter: blur(10px); backdrop-filter: blur(10px); } This is used for frosted-glass effects. 这用于磨砂玻璃效果。
Filters are often hardware-accelerated and create a compositing layer. They should be used carefully in animations or scroll-heavy pages to avoid performance issues.
滤镜通常由硬件加速并创建合成层。在动画或滚动较多的页面中,应谨慎使用它们,以避免性能问题。
1308. What is CSS Subgrid? How does it solve alignment problems in nested grids?
CSS Subgrid allows a grid item’s children to align to the parent grid’s tracks instead of creating their own independent grid tracks.
CSS Subgrid允许网格项的子元素对齐到父网格的轨道,而不是创建它们自己的独立网格轨道。
Without subgrid, nested grids do not share row and column alignment. Each grid calculates its own tracks separately. This often causes alignment issues in layouts like card grids.
These are user preference media features that detect system-level accessibility or appearance settings.
这些是检测系统级可访问性或外观设置的用户偏好媒体特性。
prefers-color-scheme detects whether the user prefers light mode or dark mode.
prefers-color-scheme 检测用户是偏好浅色模式还是深色模式。
Example:
示例:
@media (prefers-color-scheme: dark) {
@media (prefers-color-scheme: dark) { :root { :root { --bg: #1a1a1a; --bg: #1a1a1a; --text: #f0f0f0; --text: #f0f0f0; } } A common strategy is defining colors using CSS custom properties on :root, then overriding them inside the media query. 一种常见策略是在 :root 上使用 CSS 自定义属性定义颜色,然后在媒体查询内部覆盖它们。
The color-scheme property can also be declared:
color-scheme 属性也可以声明如下:
:root {
:root { color-scheme: light dark; color-scheme: light dark; } This tells the browser to adjust built-in UI elements such as scrollbars and form controls. 这告诉浏览器调整内置 UI 元素,如滚动条和表单控件。
prefers-reduced-motion detects whether the user has enabled reduced motion in operating system accessibility settings.
animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; transition-duration: 0.01ms !important; } } This reduces animations that may cause motion sickness or discomfort. 这可以减少可能引起晕动症或不适的动画。
Other related features include: - prefers-contrast
其他相关功能包括:- prefers-contrast
forced-colors
prefers-reduced-transparency These features improve accessibility by respecting user-level preferences. They allow applications to adapt automatically without requiring manual theme switches.
这些功能通过尊重用户级别的偏好来改善可访问性。它们允许应用程序自动适应,无需手动切换主题。
1310. How does the CSS will-change property work? When should and shouldn't you use it?
The will-change property informs the browser that a specific property of an element is likely to change soon. This allows the browser to prepare optimizations in advance.
.animating { will-change: transform, opacity; will-change: transform, opacity; } When an element animates properties like transform or opacity, the browser may create a new compositing layer. If that layer is created at the moment the animation begins, the first frame can stutter. will-change allows the browser to create that layer earlier. 当元素动画化属性(如 transform 或 opacity)时,浏览器可能会创建一个新的合成层。如果该层是在动画开始时创建的,第一帧可能会卡顿。will-change 允许浏览器提前创建该层。
How it works: - The browser prepares GPU compositing for the specified property.
工作原理:- 浏览器为指定属性准备 GPU 合成。
Rendering becomes smoother when the animation starts.
Memory usage increases because new layers are created. When to use it:
何时使用:
Use it only when an element is about to animate.
仅在元素即将开始动画时使用。
Use it on specific elements, not globally.
请在特定元素上使用,而不是全局使用。
When not to use it:
何时不应使用它:
Do not apply will-change to many elements. Each layer consumes memory.
不要将 will-change 应用于许多元素。每个图层都会消耗内存。
Do not use will-change: all. It prevents the browser from optimizing effectively.
不要使用 will-change: all。它会阻止浏览器进行有效优化。
Do not leave it permanently in stylesheets. It should be temporary.
不要将其永久保留在样式表中。它应该是临时的。
A common pattern is applying it before animation and removing it afterward.
常见的模式是在动画之前应用它,在动画之后移除它。
Example concept:
示例概念:
el.style.willChange = "transform";
el.style.willChange = "transform"; el.addEventListener("animationend", () => { el.addEventListener("animationend", () => { el.style.willChange = "auto"; el.style.willChange = "auto"; }); will-change improves rendering smoothness but increases memory usage. It should be used carefully and only where performance issues are measurable. will-change 能提高渲染流畅度,但会增加内存使用。它应谨慎使用,且仅在性能问题可测量时才使用。
1311. What are CSS Logical Properties? Why should we use them over physical properties?
CSS Logical Properties define layout using writing-direction–aware terms instead of fixed physical directions like left, right, top, and bottom.
CSS 逻辑属性使用与书写方向相关的术语来定义布局,而不是固定的物理方向,如左、右、上、下。
Traditional CSS uses physical properties such as: - margin-left
传统 CSS 使用物理属性,例如:- margin-left
padding-right
width
height
top
left These assume a left-to-right horizontal layout. Logical properties replace these with flow-relative equivalents that adapt automatically based on writing direction and writing mode.
Vertical writing modes (Japanese, Chinese) Why use logical properties:
为何使用逻辑属性:
They automatically adapt to different writing directions without needing separate RTL stylesheets.
它们能自动适应不同的书写方向,无需单独编写 RTL 样式表。
They support vertical writing systems where block and inline axes switch.
它们支持块轴与行轴切换的垂直书写系统。
They align with modern internationalized applications and global design systems.
它们与现代国际化应用和全球设计系统保持一致。
They provide a clearer mental model: - Inline direction = direction text flows.
它们提供了更清晰的心智模型:- 行方向 = 文本流动的方向。
Block direction = stacking direction of elements. Logical properties make layouts flexible and future-proof without duplicating styles for different languages.
逻辑属性让布局灵活且面向未来,无需为不同语言重复样式。
1312. What is the CSS clamp() function? How is it different from min() and max()?
The clamp() function restricts a value between a minimum and maximum while allowing it to scale fluidly.
clamp() 函数将值限制在最小值和最大值之间,同时允许其流畅地缩放。
Syntax:
语法:
clamp(MIN, PREFERRED, MAX)
clamp(MIN, PREFERRED, MAX) It behaves like: 它的行为类似于:
max(MIN, min(PREFERRED, MAX))
max(MIN, min(PREFERRED, MAX)) Example: 示例:
font-size: clamp(1rem, 2.5vw, 2rem);
font-size: clamp(1rem, 2.5vw, 2rem); The font size scales with viewport width (2.5vw) but never becomes smaller than 1rem and never larger than 2rem. 字体大小随视口宽度(2.5vw)缩放,但永远不会小于1rem,也不会大于2rem。
This is commonly used for fluid typography.
这通常用于流体排版。
min() returns the smallest value:
min() 返回最小值:
width: min(90%, 1200px);
width: min(90%, 1200px); The width will be whichever is smaller. 宽度将取两者中较小的值。
max() returns the largest value:
max() 返回最大值:
padding: max(1rem, 5vw);
padding: max(1rem, 5vw); The padding will be whichever is larger. 内边距将取两者中较大的值。
Comparison: - clamp() sets both lower and upper limits.
width: clamp(300px, 50%, 800px); These functions allow responsive behavior without writing media queries. They also accept mixed units directly, unlike older techniques that required complex calculations. 这些函数无需编写媒体查询即可实现响应式行为。它们还直接接受混合单位,不像旧技术那样需要复杂的计算。
1313. What are CSS Cascade Layers (@layer)? How do they affect specificity?
Cascade Layers allow grouping styles into ordered layers, giving control over precedence without relying on selector specificity tricks.
层叠层允许将样式分组到有序层中,从而控制优先级,而不依赖于选择器特异性的技巧。
Layer order is defined first:
首先定义层的顺序:
@layer reset, base, components, utilities;
@layer reset, base, components, utilities; Styles are then placed inside layers: 然后样式被放置在层内:
@layer base {
@layer base { a { a { color: blue; color: blue; } } @layer components { @layer components { .link { .link { color: green; color: green; } } Layer rules: - Later layers override earlier layers. 层规则:- 后声明的层会覆盖先声明的层。
This happens regardless of selector specificity.
Unlayered styles always override layered styles.
When using !important, earlier layers win over later ones. This changes how CSS conflicts are resolved. A low-specificity selector in a later layer can override a high-specificity selector in an earlier layer.
这改变了 CSS 冲突的解决方式。在后层中的低特异性选择器可以覆盖前层中的高特异性选择器。
Example concept:
示例概念:
A .btn class in the utilities layer can override a more complex selector in the reset layer simply because its layer is defined later.
在工具层中的一个 .btn 类可以覆盖重置层中更复杂的选择器,仅仅因为其所在的层定义得更晚。
This makes it easier to structure large projects, especially when working with third-party CSS. External libraries can be placed in early layers, and project-specific styles can be placed in later layers.
:has() selects an element based on what it contains or what follows it. Before :has(), CSS could only select children based on parents, not the other way around.
div:has(> img) { padding: 0; padding: 0; } This selects div elements that contain a direct child . 这会选择包含直接子元素 的 div 元素。
It can also react to sibling relationships:
它也可以响应兄弟关系:
h1:has(+ p) {
h1:has(+ p) { margin-bottom: 0; margin-bottom: 0; } This selects an h1 that is immediately followed by a p. 这会选择一个后面紧跟着一个 p 元素的 h1 元素。
Another practical example:
另一个实际示例:
form:has(:invalid) {
form:has(:invalid) { border: 2px solid red; border: 2px solid red;(原文为代码,保持不变) } This styles the entire form if any input inside it is invalid. 如果表单内的任何输入无效,则会对整个表单应用此样式。
Multiple conditions can be combined:
多个条件可以组合使用:
article:has(h2):has(img) {
article:has(h2):has(img) { border: 1px solid black; border: 1px solid black;(原文为代码,保持不变) } This selects articles that contain both an h2 and an img. 这会选择同时包含 h2 和 img 元素的 article 元素。
Negation is also possible:
也可以使用否定:
article:not(:has(img)) {
article:not(:has(img)) { background: #f5f5f5; background: #f5f5f5;(原文为代码,保持不变) } :has() is often called the “parent selector” because it allows selecting a parent based on its children, something that was not possible before. :has() 通常被称为“父选择器”,因为它允许基于子元素来选择父元素,这在之前是不可能的。
Browsers optimize :has() internally, but complex selectors should still be used carefully in large documents.
浏览器会在内部优化 :has(),但在大型文档中,复杂的选择器仍应谨慎使用。
1315. What are CSS Container Queries? How do they differ from Media Queries?
Container Queries allow a component to change its styles based on the size of its parent container instead of the viewport.
容器查询允许组件根据其父容器的大小(而非视口)来更改其样式。
Traditionally, responsive design relied on Media Queries, which respond to the viewport width. This works at the page level but does not help when a component appears in different layouts within the same page.
Container Queries solve this by making components context-aware.
容器查询(Container Queries)通过使组件具有上下文感知能力来解决这一问题。
To use them, you first define a container:
要使用它们,首先定义一个容器:
.card-container {
.card-container { container-type: inline-size; container-type: inline-size; container-name: card; container-name: card; } Then apply a container query: 然后应用容器查询:
@container card (min-width: 400px) {
@container card (min-width: 400px) { .card { .card { flex-direction: row; flex-direction: row; } } Here, .card changes layout only when its container reaches 400px, regardless of viewport size. 这里,.card 仅当其容器达到 400px 时改变布局,无论视口大小如何。
container-type values: - inline-size - responds to width
container-type 值: - inline-size - 响应宽度
size - responds to both width and height
normal - no size containment Key differences from Media Queries: - Media Queries respond to viewport size.
与媒体查询的关键区别: - 媒体查询响应视口大小。
Container Queries respond to parent container size.
Media Queries control page-level layout.
Container Queries control component-level layout.
The same component can render differently in a sidebar and in the main content area without JavaScript. Container query units are also available: - cqw - 1% of container width
容器查询单位也可用: - cqw - 容器宽度的 1%
cqh - 1% of container height
cqi - 1% of container inline size
cqb - 1% of container block size Container Queries are supported in all modern browsers since early 2023 and represent a major shift toward modular, reusable design systems.
Internet Protocol Configuration (IPCONFIG) is a command-line utility that gathers and displays information about current (TCP/IP) Transmission Control Protocol/Internet Protocol configuration values on the screen. In other words, it allows you to view and manage the IP address of the machine. Every time IPCONFIG is invoked, it will also refresh the DHCP ( Dynamic Host Configuration Protocol) and DNS (Domain Name System) settings. If the IPCONFIG command is executed without any parameters, it only displays the default gateway, IP address, and subnet mask of every available network adapter.
NTLDR (New Technology Loader) serves as the boot loader for all versions of the Windows NT operating system. In most cases, NTLDR runs from a primary hard drive or from a portable device like a USB flash drive or CD-ROM. Also, the NT loader is capable of loading non-NT-based operating systems with the appropriate boot sector on a file. The NTLDR consists of three major files: - NTLDR file: It is the main boot loader.
NTDETECT file: This file is required to boot an NT-based OS. It detects basic hardware information to ensure a successful boot.
boot.ini file: Contains information about the system configuration. In the event that Windows NT OS continues to fail to boot, you may receive the following NTLDR errors. Usually, the cause for NTLDR errors is the failure to boot from a non-bootable device, a damaged or not detected hard drive, BIOS outdated, file deletion or damage, or corrupted files.
If you encounter the NTLDR missing error in your system, you may try either of the following methods to resolve the problem: - Restart your computer: The NTLDR missing error might just be a fluke.
Plug out all removable media: Some accessories might be hindering the boot process. Typically, this issue appears when the BIOS attempts to load from a non-bootable external drive. Remove all external drives and removable media (CDs, floppy disks, memory cards, and USBs) to ensure the BIOS cannot be loaded from these devices.
Change the BIOS boot order: If removing the external drive isn't possible or doesn't work, you can manually adjust the boot order in BIOS/UEFI to make sure the computer boots from the internal hard drive. Step 1: Restart the computer.
步骤1:重新启动计算机。
Step 2: Press and hold F10, F8, F2, or Del to enter BIOS.
步骤2:按住F10、F8、F2或Del键进入BIOS。
Step 3: Click on the BOOT tab. Consider placing the bootable hard drive with the NT Loader files, where you have installed Windows OS, at the top of your priority list.
Step 4: Boot your computer again and check whether you still receive the NTLDR is missing error. - Upgrade your outdated BIOS: You may occasionally encounter the NTLDR missing issue if the basic input/output system (BIOS) on your computer is outdated. Accordingly, it is imperative that you install the most recent version of BIOS on your computer. It is best to contact the computer manufacturer to see how to obtain and install the latest BIOS update.
步骤4:再次启动计算机,检查是否仍收到NTLDR is missing错误。- 升级过时的BIOS:如果计算机上的基本输入/输出系统(BIOS)过时,您偶尔可能会遇到NTLDR缺失问题。因此,务必在计算机上安装最新版本的BIOS。最好联系计算机制造商,了解如何获取并安装最新的BIOS更新。
1319. State difference between Incremental and Differential Backup.
Incremental and Differential backups are two different backup strategies with the same purpose i.e., to optimize the backup space as well as the backup time.
增量备份和差异备份是两种不同的备份策略,但目的相同,即优化备份空间和备份时间。
Incremental Backup 增量备份
Differential Backup 差异备份
An incremental backup preserves all changes made since the previous full or incremental backup. It does not copy previously backed up files, only newly altered or created ones. 增量备份保留自上次完整或增量备份以来的所有更改。它不复制已备份的文件,只备份新修改或创建的文件。
Different backup strategies backup only the files that have changed since the last full backup. 不同的备份策略仅备份自上次完整备份以来更改的文件。
In this type of backup, recovery is difficult. 在这种备份类型中,恢复较为困难。
Recovery is easier with differential backups. 使用差异备份恢复更容易。
It reduces bandwidth utilization, reduces storage space requirements, and provides faster backups. 它减少带宽利用率,降低存储空间需求,并提供更快的备份。
This type of backup uses less storage space than full backups, but more than incremental backups. 这种备份类型比完整备份使用更少的存储空间,但比增量备份使用更多。
Example: Consider doing a full backup on Sunday. 示例:考虑在周日进行完整备份。
Sunday: A full backup of the data.
周日:对数据进行完整备份。
Monday: On Monday, incremental backup copies just Monday's changes without copying Sunday's backup.
周一:在周一,增量备份仅复制周一的更改,不复制周日的备份。
Tuesday: On Tuesday, the backup only retains the changes/additions made on Tuesday. This is also true for Wednesday, Thursday, and Friday. | Example: Consider doing a full backup on Sunday.
Tuesday: The backup includes Monday's and Tuesday's data.
周二:备份包括周一和周二的更改。
Wednesday: The backup comprises Monday's, Tuesday's, and Wednesday's data, and so on. Next Monday's full backup will be referenced in next week's differential backup. |
周三:备份包括周一、周二和周三的更改,依此类推。下周一的完整备份将作为下周差异备份的参考。 |
1320. State difference between an MSI and an EXE File.
MSI File: The .msi extension is used for MSI files, which are compressed packages of installer files. It contains information regarding how to add, modify, store, or remove the respective software. In the MSI file, you will find instructions, data, processes, and add-ons that are essential to running the application normally. The reason that developers prefer MSI over EXE when creating an installer for their application is that MSI is easier to create. On top of that, they also reduce the time and coding efforts involved in the process.
EXE File: In general, .exe extensions are only used for executable files that contain lines of instructions or code that can directly be run by the window's operating system. When opening the executable files received via email, users should be aware that the files run some type of code once opened. Exe files are executable programs.
1321. What do you mean by BSOD (Blue Screen Of Death)?
Blue screen of death (BSOD), also referred to as blue screen error or stop error, is an error screen displayed by the Windows operating system in the event that a fatal error is encountered. It typically occurs because of a critical condition affecting the operating system, e.g., hardware failure, or unexpected termination of a critical process. A BSOD causes Windows to enter a state of frozen mode, requiring the system to be restarted in order to continue operating.
A DHCP (Dynamic Host Configuration Protocol) reservation is a permanent assignment of an IP address. Essentially, it is a specific IP address, within the scope of a DHCP server, which is being permanently reserved for lease used by a particular DHCP client. In cases where network equipment or computer systems require a specific IP address, we will create a reservation for that computer system in the DHCP server. DHCP reservations can be configured in the DHCP server when users need a permanent IP address. The reservation includes the following elements: - Reservation Name
SMTP: SMTP (Simple Mail Transfer Protocol) is the industry-standard protocol for email transmission. SMTP is a protocol used to send, relay, or forward email messages from a mail client to a receiving mail server. An SMTP server is used for the process of sending an email message.
IMAP: IMAP (Internet Access Message Protocol) is an email protocol for managing and retrieving messages from receiving servers. The IMAP protocol is designed for message retrieval, so it cannot be used for sending emails.
1324. State difference between SMTP and POP Server.
SMTP and POP are the two protocols that control email transmission on the Internet (both send and receive). - SMTP: SMTP (Simple Mail Transfer Protocol) is a protocol that allows email to be sent from a client to a receiver server in a very simple and fast manner.
POP: By contrast, POP ("Post Office Protocol") is a protocol that allows the user (receiver) to download the message into his own inbox: it is actually the incoming server that collects the message. Today, POP3 is the most recent version.
1325. How will you backup your data if your system is infected with malware?
If you would like to successfully and safely recover data from an infected computer, you would need to extract the hard drive from the PC. It needs to be saved to a computer that has the latest virus definitions and Microsoft patches installed. Afterwards, you'd check the disc for viruses, and after they were removed, you'd be able to extract any data you needed.
The error message "Windows Cannot Connect For Updates" is mainly caused by one of the two reasons listed below: - Either the files are corrupt, missing, or have been deleted.
If update services have been disabled. The following two methods can be followed to resolve this problem: - Method 1: To troubleshoot this issue by yourself, follow these steps:
可以遵循以下两种方法来解决此问题: - 方法1:要自行解决此问题,请按照以下步骤操作: Initially, launch the Run command and type services.msc. Click the Enter key. A new window will open. Look for the option to update Windows. Then right click it and select properties. Once the startup page has opened, type 'enable' in the box and click on the Start button. Now click OK, and the problem will be resolved. - Method 2: The easiest way to fix this error is by contacting Microsoft and reporting the problem. 首先,启动运行命令并输入services.msc。按Enter键。将打开一个新窗口。查找“更新Windows”选项。然后右键单击并选择属性。启动页面打开后,在框中输入“启用”并单击“开始”按钮。现在单击“确定”,问题将得到解决。 - 方法2:修复此错误的最简单方法是联系Microsoft并报告问题。
The IEEE 1394 port, more commonly referred to as FireWire, facilitates high-speed communication between two computers or between a computer and peripheral devices (such as keyboards, digital video cameras, printers, scanners, and external hard drives). The terms FireWire refers to the types of ports, cables, and connectors that enable computers to connect to external devices.
There are two types of Outlook data files - Personal Storage Tables (PST) and Offline Storage Tables (OST), both of which store synchronized copies (either in a local drive or for offline utilization) of mailbox items - email messages, contacts, attachments, notes, etc.
PST (Personal Storage Table) is an exclusive MS Outlook file format used to store backups of calendars, contacts, messages, etc., on the user's computer from the account configured in Outlook. PST(个人存储表)是MS Outlook专有文件格式,用于在用户计算机上存储来自Outlook中配置账户的日历、联系人、邮件等备份。
In MS Outlook, OST (Offline Storage Table) is basically your offline data files. Offline Storage Files include the drafts of a user's mailbox data, for offline use on a local system. 在MS Outlook中,OST(脱机存储表)基本上是您的脱机数据文件。脱机存储文件包括用户邮箱数据的草稿,用于在本地系统上脱机使用。
It is not possible to access mailbox items offline. 无法脱机访问邮箱项目。
Provides access to mailbox items even if the system is offline or network issues are present. 即使系统脱机或存在网络问题,也能访问邮箱项目。
The PST file format is compatible with many email servers, including Exchange Server. PST文件格式与许多邮件服务器兼容,包括Exchange Server。
Support for all Exchange server versions is available. 支持所有Exchange服务器版本。
Auto-sync is not possible. 不支持自动同步。
Syncing of data occurs automatically when a network connection is available. 当网络连接可用时,数据会自动同步。
It is typically used by users who want to have a backup of their Outlook components. 通常由希望备份其Outlook组件的用户使用。
If users want to work with a domain where the internet connection is low or poor, then it comes in handy. 如果用户想在网络连接不佳或较差的域中工作,则这非常有用。
1330. How can OST mailboxes be exported or converted to PST files?
In most cases, your computer restarts in a loop because it has been affected by a hardware failure, a corrupt driver, malware infection, or due to dust and dirt. Here are some ways to troubleshoot and fix the computer restarting issue. - Turn Off the automatic restart feature: It is very annoying to see your computer continuously rebooting and there is nothing you can do about it other than turn off the Automatically restart feature.
Check the hardware issue: A faulty hardware component can cause a computer to malfunction. Therefore, you should verify that your hardware is in proper working order. Check the RAM: RAM is often the cause if your computer restarts. Check out your RAM, or the slot in which it is inserted.
检查RAM:如果计算机重启,RAM通常是原因。请检查您的RAM或插入它的插槽。
Check the CPU: Processor overheating is another issue that may result in the system restarting, so you should make sure that your CPU is functioning correctly.
检查CPU:处理器过热是可能导致系统重启的另一个问题,因此您应确保CPU正常工作。
Check your external devices: Unplug all external devices connected to your computer and check if the issue is resolved.
检查外部设备:拔掉连接到计算机的所有外部设备,检查问题是否解决。
Keeping your computer clean: A buildup of dust within your computer can cause overheating and damage to its components, resulting in frequent restarting. - Update your drivers: Drivers that are outdated or missing may cause the computer to restart because the devices are not able to communicate with your computer. Thus, you need to check and verify that all your drivers are up-to-date, and update those that aren't. Driver updates can be done manually or automatically.
Scan for viruses: Malware or virus infection is likely to result in your computer continually restarting. To prevent this, you should perform a full virus scan on your computer.
1332. What is the process of adding a system to a domain?
Follow the steps below to join a computer to a domain: - Open the Start screen, then type Control Panel into the search box, and press Enter to open it.
按照以下步骤将计算机加入域:- 打开开始屏幕,然后在搜索框中输入控制面板,并按Enter打开它。
Go to System and Security, and click System.
Scroll down to Computer name, domain, and workgroup settings, and then click on Change settings.
From the Computer name tab, select Change.
Click on Domain under Members of, type the domain name you wish the computer to join, and click OK.
Finally, Click OK and restart the computer.
1333. State difference between RAS and VPN Server.
The difference between RAS and VPN server is as follows:
RAS和VPN服务器之间的区别如下:
RAS
VPN
RAS (Remote Access Services) can be defined as any combination of hardware and software components compatible with IT devices that allow remote access to tools and information stored on these devices. 远程访问服务(RAS)可定义为与IT设备兼容的硬件和软件组件的任意组合,允许远程访问这些设备上存储的工具和信息。
A virtual private network (VPN) is a network that is used to create a private, secure connection that enables you to communicate over a public network in a confidential way. 虚拟专用网络(VPN)是一种用于创建私有、安全连接的网络,使您能够以保密方式在公共网络上进行通信。
Basically, it is the industry-standard method of setting up remote connections. 基本上,它是设置远程连接的行业标准方法。
It was specially designed for medium and large-sized networks. 它专为中型和大型网络设计。
Data is not authenticated or encrypted when transferred over RAS. 通过RAS传输数据时不进行认证或加密。
Data is authenticated or encrypted when transferred over a VPN. 通过VPN传输数据时进行认证或加密。
The price of it is quite high. 其价格相当高。
It is extremely cost-effective. 它极具成本效益。
It is a very unstable system. 它是一个非常不稳定的系统。
The system is stable and secure. 该系统稳定且安全。
It isn't a fun experience dealing with the system. 处理该系统并不是一种愉快的体验。
Tree Domain: A collection of domains which are connected together in an Active Directory hierarchy is referred to as a tree, a tree domain, or a domain tree. The tree domain contains multiple domains that can communicate with each other by using trusts. They can communicate one way or two ways.
Child Domain: A domain tree is formed on the basis of the parent-child hierarchy. Child domains are basically a logical grouping of network objects (domains) beneath a parent domain in an Active Directory hierarchy.
Useful Resources
有用资源
Technical Support Interview Questions
Application Support Interview Questions
Linux Interview Questions
Operating System Interview Questions
Networking Interview Questions
Interview Preparation Articles
Technical Interview Guide
1335. What is the next level after desktop support engineer?
Since you are a Desktop Engineer, you can grow your career further by gaining experience in server administration. This can comprise Windows/Unix administration or even Cisco networking that can provide a lot of opportunities for you. A desktop support specialist may choose to pursue a computer-related position such as database administrator, network administrator, computer network architect, SharePoint administrator, and technology director.
This question provides insight into what motivates you as a candidate. Recruiters want to know if you are motivated by the attractive compensation plan or if you want to help solve problems. - Show your knowledge of the industry and your potential value if hired.
Aside from money, talk about other aspects of the role that make you passionate. What drives you? Is it a passion for troubleshooting computers or a deep understanding of programming and its applications?
Make sure that you understand how vital desktop support is to the smooth operation of the entire office since most departments are reliant on IT support. Sample Answer:
示例回答:
“Choosing a career as a technical support specialist has enabled me to pursue my passion for computers and solve the problems of others. Although technical knowledge is often taken for granted, it can make or break clients' businesses and operations. It provides an easier way to get into almost any tech industry while also improving your technical skills. Taking on a position as a desktop support technician will allow me to make customers' lives and businesses easier while continuing to do what I enjoy doing."
In India , a Desktop Support Engineer's salary ranges from Rs 1.3 Lakhs to Rs 3.5 Lakhs per annum, with an average annual salary of Rs 2.2 Lakhs . In the United States , a computer engineer earns an average salary of $52,133 per year .
Your response to this question demonstrates your commitment to that specific employer and will provide insight into whether you have researched the company beforehand. Don't miss the opportunity to demonstrate your genuine passion for the organization. - Demonstrate to the recruiter that you understand the company's mission and vision and desire to contribute to its success.
You might mention how you like the company culture or employee development programs.
Perhaps you could also mention whether the organization has a public service or environmental initiative that resonates with you. Sample Answer:
示例回答:
“Considering that your products contribute to lessening the carbon footprint and making food production more environmentally friendly, this is why I applied to your company. The work you do, especially in developing countries, makes a positive impact on millions of lives around the world. It will enrich my career and my personal life as well. Having an interest in network systems, computer systems, and interacting with people, I believe working for your organization would be an excellent stepping stone into a career as a desktop engineer”.
The Prototype Pattern creates new objects, but instead of returning uninitialized objects, it returns objects with values copied from a prototype - or sample - object. The Properties pattern is another name for the Prototype pattern.
The initialization of business objects with values that match the database's default settings is an example of where the Prototype pattern comes in handy. The default values from the prototype object are replicated into a newly generated business object.
The Prototype pattern is rarely used in traditional languages, but JavaScript, as a prototypal language, employs it in the creation of new objects and prototypes.
The WeakMap is a collection of key/value pairs, just like the Map. The keys of WeakMap, on the other hand, must be objects, whereas the values can be anything. The object references in the keys are held weakly, which means that if there is no other reference to the object, it will be eligible for garbage collection. WeakMap, but not Map, permits the garbage collector to complete its duty. The array of keys would preserve references to key objects in manually constructed maps, prohibiting them from being garbage collected. References to key objects in native WeakMaps are held "weakly," which means they do not hinder garbage collection if there is no other reference to the object. The Map API and the WeakMap API are the same.
WeakMap keys, on the other hand, are not enumerable, unlike Map objects. There are also no methods that return a list of keys. If they were, the list would be non-deterministic because it would be dependent on the state of garbage collection. A Map should be used if we need a list of keys.
The main benefit of utilising an arrow function as a method within a constructor is that the value of this is set at the moment of function generation and cannot be changed later. As a result, whenever the constructor is used to create a new object, this refers to that object.
const circle = new Shape('Circle'); const square = new Shape('Square'); const square = new Shape('Square');
circle.showName1(); // Circle
circle.showName1(); // Circle circle.showName2(); // Square circle.showName2(); // Square
// The regular function can have its 'this' value changed, but the arrow function cannot
// 普通函数的'this'值可以被改变,但箭头函数不能 circle.showName1.call(square); // Square (because "this" is now the square object) circle.showName1.call(square); // Square(因为"this"现在是square对象) circle.showName2.call(square); // Circle circle.showName2.call(square); // Circle
circle.showName1.apply(square); // Square (because 'this' is now the square object)
circle.showName1.apply(square); // Square(因为'this'现在是square对象) circle.showName2.apply(square); // Circle circle.showName2.apply(square); // Circle
circle.showName1.bind(square)(); // Square (because 'this' is now the square object)
circle.showName1.bind(square)(); // Square(因为'this'现在是square对象) circle.showName2.bind(square)(); // Circle circle.showName2.bind(square)(); // Circle
var showNameFromPic1 = circle.showName1;
var showNameFromPic1 = circle.showName1; sayNameFromPic1(); // undefined (because 'this' is now the pic object) sayNameFromPic1(); // 未定义(因为此时'this'指向pic对象)
var showNameFromPic2 = circle.showName2;
var showNameFromPic2 = circle.showName2; showNameFromPic2(); // Circle showNameFromPic2(); // Circle The major point here is that for a normal function, this can be modified, but for an arrow function, the context is always the same. You won't have to worry about the context changing if you pass your arrow function around to other areas of your application. 这里的关键点是,对于普通函数,this可以被修改,但对于箭头函数,上下文始终相同。如果你将箭头函数传递到应用程序的其他区域,就不必担心上下文发生变化。
Variable Hoisting does not apply to let bindings in ES6, so let declarations do not rise to the top of the current execution context. A ReferenceError is thrown if the variable in the block is referenced before it is initialized (unlike a variable declared with var, which will just possess the undefined value). From the beginning of the block until the initialization is performed, the variable is in a "temporal dead zone."
console.log(a); // undefined console.log(b); // causes ReferenceError: aLet is not defined console.log(b); // 导致ReferenceError: aLet is not defined var a = 1; var a = 1; let b = 2; let b = 2;
1343. What is the difference between Set and WeakSet in ES6?
Set : By using the Set() class, users can define an array-like heterogeneous iterable object, which will consist of distinct values. The elements should not just be distinct by values but also by types. i.e. "2" and 2 will be considered as different.
set1.size; // 4 set1.clear(); // Set Cleared set1.clear(); // Set 已清空 WeakSet() : A WeakSet() is a collection that is similar to a Set because it retains unique values; but it can only hold Objects. If an object in your WeakSet has no other reference variables left, it will be removed automatically. WeakSet() : WeakSet() 是一个类似于 Set 的集合,因为它保留唯一值;但它只能包含对象。如果 WeakSet 中的某个对象没有其他引用变量,它将被自动移除。
var weakSet1 = new WeakSet([{x:1}]);
var weakSet1 = new WeakSet([{x:1}]); var ob1 = {o:1}; var ob1 = {o:1}; var ob2 = {o:2}; var ob2 = {o:2};
weakSet1.has(ob1); //false
weakSet1.has(ob1); //false weakSet1.add(ob1); weakSet1.add(ob1); weakSet1.add(ob2); weakSet1.add(ob2); weakSet1.has(ob2); // true weakSet1.has(ob2); // true delete ob1; // you can't delete objects in this way. Use scope to execute this. delete ob1; // 你不能以这种方式删除对象。请使用作用域来执行此操作。 myWeakSet.has(ob1); // false, because you deleted ob1, so WeakSet releases it automatically myWeakSet.has(ob1); // false,因为你删除了ob1,所以WeakSet会自动释放它 myWeakSet.delete(ob2); // ob2 deleted from the set myWeakSet.delete(ob2); // ob2已从集合中删除 myWeakSet.add(1); // ERROR, no primitive value myWeakSet.add(1); // 错误,不允许原始值 | Set | WeakSet |
A set can contain all types of values. 集合可以包含所有类型的值。
A weakSet can only contain objects. WeakSet只能包含对象。
Use .size to find the number of elements. 使用.size查找元素数量。
Use .length to find the number of elements. 使用.length查找元素数量。
.forEach() is available for iteration. .forEach()可用于迭代。
.forEach() is not available for iteration. .forEach()不可用于迭代。
Nothing is auto-destroyed. 没有自动销毁的行为。
An element object will be auto released to the garbage collector if it has no other reference left. 如果没有其他引用,元素对象会被自动释放给垃圾回收器。
Const is a property that applies to bindings ("variables"). It creates an immutable binding, which means you can't change its value.
const 是适用于绑定(“变量”)的属性。它创建了一个不可变的绑定,这意味着你无法改变它的值。
const a = {
const a = { b: "apple" b: "apple" }; let c = { let c = { d: "mango" d: "mango" }; a = c; // ERROR "a" is read-only a = c; // 错误 “a” 是只读的 Object.freeze() is a function that works with values, primarily object values. It makes an object immutable, meaning that its properties cannot be changed. Object.freeze() 是一个作用于值的函数,主要作用于对象值。它使对象不可变,意味着其属性不能被更改。
freeze() returns the same object that was supplied to it as a parameter. It does not make a frozen copy. If the parameter to this method is not an object (a primitive) in ES5, a TypeError will occur. A non-object argument in ES6 will be treated as if it were a frozen regular object and will be returned.
let a = { b: "apple" b: "apple" }; let c = { let c = { d: "mango" d: "mango" }; Object.freeze(a); Object.freeze(a); a.b = "kiwi"; //TypeError: Cannot assign to read only property 'name' of object a.b = "kiwi"; //类型错误:无法为对象的只读属性“name”赋值 console.log(a); console.log(a);
1346. Why does the following not work as an IIFE (Immediately Invoked Function Expressions) ? What needs to be modified in order for it to be classified as an IIFE?
function f()(); The JavaScript parser interprets the function f()(); as function f() and (); where the former is a function declaration while the latter (a pair of brackets) is an attempt to execute a function without specifying a name, resulting in Uncaught SyntaxError: Unexpected token ). JavaScript解析器将function f()();解释为function f()和();,其中前者是函数声明,而后者(一对括号)是尝试在没有指定名称的情况下执行函数,导致未捕获的语法错误:意外的标记“)”。
(function f())() and (function f()()) are two ways to fix it that involve adding more brackets. These functions are not available in the global scope, and you can even omit their names if you don't need to refer to them within the body.
You can also use the void operator: void function f()(); .However, there is a drawback in this strategy. Because the evaluation of a given expression is always undefined, you can't use your IIFE function if it returns anything. Consider the following scenario:
还可以使用void运算符:void function f()();。然而,这种策略有一个缺点。因为给定表达式的求值结果总是undefined,如果你的IIFE函数返回任何值,则无法使用它。考虑以下场景:
// Don't add JS syntax to this code block to prevent Prettier from formatting it.
// 不要向此代码块添加JS语法,以防止Prettier格式化它。 const f = void const f = void function b() { function b() { return 'f'; return 'f'; }();
console.log(f); // undefined
console.log(f); // undefined
1347. Explain Internationalization and Localization.
These are JavaScript standard APIs that assist with operations such as collation, number formatting, currency formatting, and date and time formatting. - Collation: It is a method for searching and sorting strings within a collection. It has a locale argument and is Unicode-aware.
Number Formatting: Localized separators and digit grouping can be used to format numbers. Style formatting, numeral system, percent, and precision are among the other items.
Currency formatting: Currency symbols, localized separators, and digit grouping are the most common ways to format numbers.
Date and time formatting: Localized separators and ordering are used for formatting. The format can be short or long, and other characteristics such as location and time zone can be included.
Webpack is a tool for bundling javascript files for usage in browsers. Webpack analyses the application and generates the bundles by creating a dependency graph that maps each module of the project required. It enables you to execute the environment that was hosted by Babel. A web pack has the advantage of combining numerous modules and packs into a single JavaScript file. It includes a dev server, which aids with code updates and asset management.
In asynchronous programming, streams are used to provide a sequence of data in an asynchronous manner. Similar to a pipe, we put a value on one end and a listener receives it on the other. Several listeners can be put into one stream, and they'll all get the same value when they're put in the pipeline. It's possible to create and manage streams through the SteamController.
The Stream API provides the await for and listen() methods for processing streams. Streams can be created in many ways, but they can only be used in the same manner. Here is an example:
Stream API 提供了 await for 和 listen() 方法来处理流。流可以通过多种方式创建,但使用方式相同。下面是一个示例:
Future sumStream(Stream stream) async {
Future sumStream(Stream stream) async { var sum = 0; var sum = 0; await for (var value in stream) { await for (var value in stream) { sum += value; sum += value; } return sum; return sum; }
The streams’ functionality is part of Dart and is inherited by Flutter. In Flutter, there are two kinds of streams:
流的功能是Dart的一部分,并由Flutter继承。在Flutter中,有两种流:
Single Subscription Streams: These streams deliver events sequentially. They are considered as sequences contained within a larger whole. These streams are used when the order in which events are received matters, such as reading a file. There can be only one listener throughout the sequence, and without a listener, the event won't be triggered.
Broadcast Streams: These streams deliver events to their subscribers. Upon subscribing to events, subscribers are immediately able to start listening to them. These are versatile streams that allow several listeners to listen simultaneously. Furthermore, one can listen again even after canceling a previous subscription.
A Flutter SDK (Software Development Kit) enables developers to build applications for mobile, web, and desktop using a single codebase. Flutter SDK includes the following features: - Dart SDK
For any dart application, the initial execution requires a fair amount of time. Therefore, to solve this problem, flutter has two features: Hot Reload and Hot Restart, which reduce the execution time of our app after we run it. - Hot Reload: It is considered an excellent feature of flutter that takes approximately one second to perform its functionality. With this function, you can make changes, fix bugs, create UIs, and add features easily and quickly. By utilizing the hot reload feature, we can quickly compile the new code in a file and send it to Dart Virtual Machine (DVM). As soon as DVM completes the update, it updates the app's UI. The preserved state is not destroyed in hot reload.
Hot Restart: It has a slightly different functionality as compared to a hot reload. In this, the preserved states of our app are destroyed, and the code gets compiled again from the beginning. Although it takes longer than a hot reload, it's faster than a full restart function.
BuildContexts are used to identify or locate widgets in widget trees. Each widget has its own BuildContext, i.e., one BuildContext per widget. Basically, we're using it to find references to other widgets and themes. In addition, you can utilize it to interact with widget parents and access widget data.
Unit tests: Using unit testing, you can test a class or method. Unit tests do not check for rendering to screen, interacting with external services, or user interactions.
Widget tests: Using widget testing, you can test a single widget. This ensures that the widget's UI looks as expected and responds appropriately to events. In other words, it ensures that the widget design, rendering, and interaction with other widgets are up to the mark.
Integration tests: Using Integration testing, you can test the critical flows of the entire app. It is important to check whether all widgets and services work together as expected. You can also use it to measure and benchmark the performance of your app.
Whether you are building a mobile app or a web application, State Management is crucial. Using it, states of various UI controls are centralized to handle data flow across an application. It can be a text field, radio button, checkbox, dropdown, toggle, form, and so on. In Flutter, state management can be categorized into two types as follows: - Ephemeral State: Ephemeral state is also called UI state or local state, and it pertains to a particular widget. In other words, it is a state that is contained within the specific widget. By means of StatefulWidget, Flutter provides support for this state.
App State: This is different from the ephemeral state since it is a state that we intend to share across different parts of the app and which we want to maintain between sessions. These types of states can thus be used globally. By means of scoped_model, Flutter provides support for this state. The following diagram gives a better explanation of the differences between ephemeral and app states:
The pubspec.yaml file, also known as 'pubspec', is a file that is included when you create a Flutter project and is located at the top of the project tree. This file contains information about the dependencies like packages and their versions, fonts, etc., that a project requires. It makes sure that the next time you build the project, you will get the same package version. Additionally, you can set constraints for the app. During working with the Flutter project, this configuration file of the project will be required a lot. This specification is written in YAML, which can be read by humans. The following are included in this file: - General project settings, like name of the project, version, description, etc.
The shortened version of in-between animation is tween animation . The start and endpoints of an animation must be specified in tween animation. Using this method, the animation can begin at the beginning and can progress through a series of values until it reaches the endpoint. Transition speed and duration are also determined by using the tween animation. Calculating the transition from the beginning to the end will be easier with the widget framework.
As far as Flutter is concerned, the following database packages are widely accepted and mostly used:
就Flutter而言,以下数据库包被广泛接受且最常用:
Firebase database: It gives users access to and control over the cloud database. Firebase basically provides a NoSQL database for Flutter apps with the ability to manage data retrieval and storage through JSON protocol. Data sync and quick loading make it one of the most suitable options for Flutter Apps. Features : - NoSQL DB
Storage SQFlite database: Users can access and modify the SQLite database using this. With this database, you have full control over your database, queries, relationships, and anything you could desire. Features : - Serverless
The provider is built using widgets. You can use all the objects in the provider as if they were just part of Flutter with the new widget subclasses it creates. This also means that the provider is not cross-platform. The provider is the simplest way to handle state management. Basically, it works on the concept of PUB-SUB i.e., there is one provider and several subscribers.
Until the async method is finished, await interrupts the process flow. Await generally means: Wait here until this function is finished so that you can get its return value. Await can only be used with async. Using this, all currently running functions are put on hold until PF nature is complete.
Container: In this parent widget, multiple child widgets can be easily controlled and handled by adjusting their size, padding, and color efficiently. We can wrap a widget in a container widget if it needs any styling, like a color, a shape, or a size constraint, etc.
SizedBox: This is a specific size box. It does not allow us to set the widget's color or decoration, unlike Container. In this case, we only need to resize the widget that is passed as a child. In other words, it forces its child widget to have a specific size.
Null-aware operators in dart allow you to make computations based on whether or not a value is null. Dart provides some useful information to handle the null values. - The "??=" assignment operator: It assigns a value to a variable only if it is null.
Dart中的空值感知运算符允许你根据值是否为null来进行计算。Dart提供了一些有用的信息来处理null值。- “??”=赋值运算符:它仅在一个变量为null时才为其赋值。 int a; // a is initialized with null value. int a; // a被初始化为null值。 a ??= 10; a ??= 10; print(a); // It will print 10. - The "??" null-aware operator: This one computes and returns the value between two expressions. In the first step, expression 1 is checked for nullness, and if it is, its value is returned; otherwise, expression 2 is evaluated, and its value is returned. print(a); // 它将打印10。- “??”空值感知运算符:该运算符计算并返回两个表达式之间的值。第一步,检查表达式1是否为null,如果是,则返回其值;否则,求值表达式2并返回其值。 print(5 ?? 10); // It will print 5. print(5 ?? 10); // 它将打印5。 print(null ?? 10); // It will print 10. - The “?.” Safe Navigation Operator: It is also known as the Elvis operator. It is possible to use the ?. operator when calling a method/getter on an object, as long as the object isn't null (otherwise, the method will return null). print(null ?? 10); // 它将打印10。- “?.”安全导航运算符:它也被称为Elvis运算符。只要对象不为null(否则方法将返回null),就可以在调用对象的方法/获取器时使用?.运算符。 obj?.child?.child?.getter //The expression returns null if obj, child1, or child2 are null. If not, the getter is called and returned. obj?.child?.child?.getter //如果obj、child1或child2为null,则表达式返回null。如果不是,则调用并返回获取器。
Conclusion:
结论: Flutter is a mobile technology that is among the most innovative and booming in the mobile market as the next revolutionary thing right now. Although it is a relatively new framework for developing cross-platform applications, its popularity is soaring due to which there is an increase in demand for Flutter developers. Flutter是一种移动技术,作为当前下一个革命性事物,它在移动市场中属于最具创新性和蓬勃发展之一。尽管它是一个相对较新的跨平台应用开发框架,但其受欢迎程度正在飙升,因此对Flutter开发者的需求也在增加。
Important Resources Flutter Projects Flutter vs Android Studio Flutter vs React Native
The ‘use strict’ statement sets a few restrictions in the script. Typically, it is utilized to facilitate the strict mode of the script, making sure there could be no loose coupling like undeclared variables.
MySQL: It is a Relational Database Management System (RDBMS), which makes use of SQL as a standard language to handle its database. Like different relational database management systems, MySQL makes use of a table-like structure to stow data.
MongoDB: MongoDB is a NoSQL database that utilizes the JSON-like structure to stow data elements. To modify and access data in MongoDB, the programmer ought to make use of the MongoDB Query Language (MQL).
Generally, the function name is defined when we define the function itself, in normal user-defined functions, but in the case of an anonymous function, the function name is not defined. Here we make use of an assignment operator and variable to stow the function as an object, then utilizing that variable, we will be capable to invoke the function itself.
CSS image sprites assist to render numerous images in a single line image. In a nutshell, the CSS sprites merge numerous photos into a single large image. If a web page comprises different images, then it would raise its loading time as for every image the browser has to send a distinct HTTP request, but with the help of sprites, we have a single image to request.
Here, value and type are the attributes of HTML, but when the statement is read by the browser and parses this code it will make a DOM with different properties, like accept, autofocus, accessKey, baseURI, checked, childElementCount, align, alt, childNodes, children, classList, className, attributes, and clientHeight.
var data = document.querySelector(input); // here we created a document object of input tag
var data = document.querySelector(input); // 这里我们创建了input标签的文档对象 console.log(input.getAttribute('value')); // tech // getting the attribute value console.log(input.getAttribute('value')); // tech // 获取属性值 console.log(input.value); // tech // getting the property of the input object console.log(input.value); // tech // 获取input对象的属性
== denotes abstract equality operator, and it inspects if two values are equal or not apart from their data types. Automatically, it transforms the type of both the operands and compares them.
1=='1'; //true 1==1; // true 1==1; // true === denotes identity equality operator, and it inspects the values of both the operands and their data type. The outcome of the operation will be true considering both the operands are equal and have the same data type, or else it returns false. === 表示严格相等运算符,它会检查两个操作数的值及其数据类型。只有当两个操作数相等且数据类型相同时,运算结果才为 true,否则返回 false。
Example:
示例:
1===1 //true
1===1 //true 1==='1' // false 1==='1' // false
1373. In an image tag, what is the benefit of the srcset attribute?
srcset is utilized when we wish to generate several resolutions of the exact image on several devices. This improves the UI. The browser will display low resolution on low-end devices, and high resolution of an image on high-end devices.
It is sent when we wish to recover data from the server. GET request is the most typically used HTTP request. 当我们希望从服务器恢复数据时发送。GET 请求是最常用的 HTTP 请求。
HEAD
The HEAD is a reaction that is the same as the GET request but doesn’t possess a message-body in the response. The HEAD request method is beneficial in retrieving meta-data that is documented as per the headers, without transferring the entire content. The method is commonly utilised when testing hypertext links for recent change, accessibility, and validity. HEAD 是一种与 GET 请求相同的响应,但响应中不包含消息体。HEAD 请求方法在检索按头部记录的元数据时很有用,而无需传输整个内容。该方法通常用于测试超文本链接的最近更改、可访问性和有效性。
TRACE
TRACE requests are implemented to invoke a remote, application loop-back test along the path to the target resource. The TRACE method lets users to witness whatever message is being received at the other end of the request chain so that they can utilise the data for testing or diagnostic functions. TRACE 请求用于沿到目标资源的路径调用远程应用程序回环测试。TRACE 方法让用户能够看到请求链另一端接收到的任何消息,以便他们可以利用这些数据进行测试或诊断功能。
POST
This request is utilized to transmit data from the user to the server. By submitting web forms, these requests can be made. The POST request is generally utilized to build data in the database.For instance, when we build a new account on any webpage, we make use of the POST request. 此请求用于将数据从用户传输到服务器。通过提交 Web 表单,可以发出这些请求。POST 请求通常用于在数据库中构建数据。例如,当我们在任何网页上创建新账户时,会使用 POST 请求。
PUT
It is identical to POST, but it is utilized to revise the existing data on the server. For instance, when we wish to revamp our complete account on a web page, we utilize the PUT request. 它与 POST 相同,但用于修改服务器上的现有数据。例如,当我们希望在网页上更新我们的完整账户时,会使用 PUT 请求。
PATCH
It is identical to PUT and is utilized when we wish to revise a certain field of our data. For instance, when we just wish to update our name or any additional information about our account, we can make use of the PATCH request. 它与 PUT 相同,用于当我们希望修改数据的特定字段时。例如,当我们只想更新姓名或账户的任何其他信息时,可以使用 PATCH 请求。
Any time one URL needs to be redirected to another permanently, a 301 redirect should be used. A 301 redirect implies that bots and visitors that come on that page will be taken to the new URL. Link equity is also passed to the new URL via a 301 redirect. 当某个 URL 需要永久重定向到另一个 URL 时,应使用 301 重定向。301 重定向意味着访问该页面的机器人和访客将被带到新 URL。链接权重也会通过 301 重定向传递给新 URL。
302 redirect is just like a 30, where it passes visitors and bots to the new page, but it may not pass along link equity. It is not recommended using 302 redirects for permanent changes. 302 重定向类似于 301,它将访客和机器人带到新页面,但可能不会传递链接权重。不建议对永久更改使用 302 重定向。
HTTP Status Code 404 - Not Found HTTP 状态码 404 - 未找到
This implies the server did not find the file or page that the browser is requesting. 404s don’t show whether the missing resource or pages are missing temporarily or permanently. You can check what this appears to be on your site by writing in a URL that doesn’t exist. Every site will have some pages that display the 404 status codes. 这表示服务器未找到浏览器请求的文件或页面。404 不显示缺失的资源或页面是暂时还是永久缺失的。您可以通过输入不存在的 URL 来检查网站上显示的内容。每个网站都会有一些显示 404 状态码的页面。
HTTP Status Code 200 - OK HTTP 状态码 200 - 正常
This is the ideal status code for a properly functioning page. 这是功能正常页面的理想状态码。
HTTP Status Code 410 - Gone HTTP 状态码 410 - 已删除
A 410 implies the page is no longer available from the server and they have set no forwarding address. Any links you present on your site that are directed to a 410 page are sending visitors and bots to a dead resource. 410 表示页面不再可从服务器获得,且未设置转发地址。您网站上指向 410 页面的任何链接都会将访客和机器人引向无效资源。
HTTP Status Code 500 - Internal Server Error HTTP 状态码 500 - 内部服务器错误
This status code shows a problem with the server and will affect access to your site. Bots and human visitors alike will get lost, and your link equity will go nowhere fast. 此状态码显示服务器存在问题,并会影响对您网站的访问。机器人和人类访客都会迷失,您的链接权重将无处可去。
HTTP Status Code 503 - Service Unavailable HTTP 状态码 503 - 服务不可用
503 response, shows that the server is unavailable. This could be because of temporarily overloading the server or maintenance of the server. 503 响应表示服务器不可用。这可能是由于服务器临时过载或服务器维护所致。
Additional Useful Resources
其他有用资源
Front End Developer Salary in India – For Freshers & Experienced
Front-End Developer Resume Sample (PDF): Full Guide and Example
Best Front End Frameworks
Difference Between Frontend and Backend – Frontend Vs Backend
IN a JSON method, stringify is used to transform a JavaScript object into a string. JSON is a common structure to receive and send data between the web server and the client, and when we wish to send data to the webserver, the object ought to be a string.
在 JSON 方法中,stringify 用于将 JavaScript 对象转换为字符串。JSON 是 Web 服务器和客户端之间接收和发送数据的常见结构,当我们需要向 Web 服务器发送数据时,对象应为字符串形式。
Example:
示例:
1376. State all the elements of the CSS Box Model.
When you're preparing for your Front-end developer interview, try to code most of your layout without taking a glance at the result till the end. If CSS, HTMLare the most important aspect of front-end development, then JavaScript tops the list of important skills to own. Organisations will spend a lot of time during your interview to test your understanding of Javascript.
在准备前端开发人员面试时,尽量在编码布局时不查看结果,直到最后完成。如果 CSS 和 HTML 是前端开发最重要的方面,那么 JavaScript 则是拥有的重要技能列表中的首要项。公司在面试时会花大量时间测试你对 JavaScript 的理解。
1378. Why should we hire you as frontend developer?
Freshers: While interviewing for front-end developer jobs for freshers you can come across this question. The best answer would be, " I have just begun my career, and do not have practical achievements, but I wish to explore and experience my potential by giving the best services to the company. It will be my privilege to work with your organization."
Experienced: The best answer would be, “You should hire me for the role of front-end developer owing to my proven ability to create effective front-end user interfaces in line with contemporary best practices. I have experience working with JavaScript, along with the React framework, to create front-end applications.”
1379. What is the most challenging work you have ever done as a front-end developer?
The biggest challenges faced as a front-end developer are: - Make sure each UI element like button, link navigation, works as planned despite the user having JavaScript or cookies disabled.
作为前端开发人员面临的最大挑战有:- 确保每个 UI 元素,如按钮、链接导航,在用户禁用 JavaScript 或 cookies 的情况下也能按预期工作。
Make sure everything looks similar across all browsers.
As per the payscale, freshes, front-end developer gets an average of ₹305,498 per annum. An intermediate developer's salary is ₹452,073 on average. A senior developer can earn an average of ₹806,231.
Yes, a front-end developer is regarded as a good career choice. It is in demand by top-tier players like Deloitte, Amazon, HCL, etc. Furthermore, the annual pay for a front-end developer is lucrative. In a nutshell, it is an in-demand position, good pay, and new learning each day.
Front-end development is considered as the programming which concentrates on the visual elements of an app or website that a user will interact with. Back end development concentrates on the side of a website that the user can't see, meaning the server-side.
One of the most popular features of ES6 is the "arrow functions" (also known as "fat arrow functions"). Arrow functions are a new way to write concise functions. Arrow functions offer a compact alternative to traditional function expressions, but they have limitations and cannot be used in every case.
function timesTwo(params) { return params * 2 return params * 2 } timesTwo(5); // 10 timesTwo(5); // 10 The same function can also be expressed as an arrow function in ES6 as follows: 同样的函数也可以用 ES6 中的箭头函数表示,如下所示:
var timesTwo = params => params * 2
var timesTwo = params => params * 2 timesTwo(5); // 10 timesTwo(5); // 10 Differences & Limitations: - Has no bindings to 'this' or 'super', so it shouldn't be used as a method. 差异与限制:- 没有对 'this' 或 'super' 的绑定,因此不应将其用作方法。
Has no new.target keyword.
The call, apply, and bind methods are not suitable since they rely on establishing scope.
Not suitable for use as constructors.
Not possible for an arrow function to use the yield keyword within its body, etc.
1385. State difference between normalization and denormalization.
Normalization and denormalization are the two main methods of altering the structure of a database.
规范化和反规范化是改变数据库结构的两种主要方法。
Normalization 规范化
Denormalization 反规范化
Normalization involves removing redundant data (multiple copies of data) from a database and storing consistent, non-redundant data. 规范化涉及从数据库中移除冗余数据(数据的多个副本),并存储一致的、非冗余的数据。
It involves combining data from multiple tables into a single so that it can be queried quickly. 它涉及将多个表中的数据组合到单个表中,以便可以快速查询。
It primarily focuses on clearing out unused data and reducing duplicate data and inconsistencies from a database. 它主要侧重于清理未使用的数据,并减少数据库中的重复数据和不一致性。
On the other hand, denormalization aims to achieve faster query execution by adding data redundancy. 另一方面,反规范化旨在通过增加数据冗余来实现更快的查询执行。
During normalization, tables are reduced in number due to the reduction of data in the database. 在规范化过程中,由于数据库中数据的减少,表的数量会减少。
Denormalization, on the other hand, involves integrating data into the same database and therefore the number of tables to store the data increases. 相反,反规范化涉及将数据整合到同一数据库中,因此存储数据的表数量会增加。
Data integrity is maintained by normalization. A change to the data in the table will not impact its relationship with the other table. 规范化可维护数据完整性。表中数据的更改不会影响其与其他表的关系。
Data integrity is not maintained by denormalization. 反规范化不维护数据完整性。
It optimizes the use of disk space. 它优化了磁盘空间的使用。
It does not optimize disk space. 它不优化磁盘空间。
1386. In Java, what is a connection leak? How can you fix this?
If a connection is opened and forgotten about, this is known as a "leak" since each time it occurs, a connection is no longer available for reuse. Connection leaks occur when some database requests or transactions are not closed properly or are not committed, causing the connections to be abandoned and closed permanently.
Java developers commonly experience Connection Leaks when using Connection Pools. In the case where there is a section of code that fails to close a connection properly, a connection will leak from the pool each time the section of code is executed. Eventually, if this situation continues, the pool will run out of connections, which is known as Pool Exhaustion. The application will hang once all available connections have been leaked. We can fix this by closing the connection and paying particular attention to any error handling code.
Callback functions are functions that can be passed to another function as arguments and executed there to complete a routine or action. Those functions depend on one another, so it could get quite messy with so many callback functions nested in so many layers. This is what is referred to as callback hell.
As an alternative to callbacks in JavaScript, promises are used to handle asynchronous operations. In addition to handling multiple asynchronous operations, they provide better error handling than callbacks. Promises can be a better way for a user to read the code effectively and efficiently, especially when that particular code performs multiple asynchronous operations. The Promise object represents the result of an asynchronous operation (or its failure) and the resulting value. The promise is in one of the following states: - Pending: In its initial state, neither fulfilled nor rejected.
GET and POST are two different HTTP request methods.
GET和POST是两种不同的HTTP请求方法。
GET
POST
This method is used to request data from a certain resource (via some API URL). 此方法用于从特定资源(通过某个API URL)请求数据。
This method is used to send or write data to be processed to a specific resource (via some API URL). 此方法用于将待处理的数据发送或写入特定资源(通过某个API URL)。
If you use the GET method to send data, the data is added to the URL, and a URL can be up to 2048 characters in length. Therefore, it has restrictions on data length. 如果使用GET方法发送数据,数据会添加到URL中,而URL长度最多可达2048个字符。因此,它对数据长度有限制。
It does not impose such limitations. 它不施加此类限制。
In comparison to POST, GET is less secure since data is sent as part of the URL. Passwords and other sensitive information should never be sent using GET. 与POST相比,GET安全性较低,因为数据作为URL的一部分发送。密码和其他敏感信息绝不应使用GET发送。
It is a little safer to use POST than GET because the parameters are not saved in the browser history or the web server logs. 使用POST比GET稍微安全一些,因为参数不会保存在浏览器历史记录或Web服务器日志中。
Everyone can see the data in the URL. 每个人都可以看到URL中的数据。
There is no data displayed in the URL. URL中没有显示数据。
1389. Explain the Restful API and write its usage.
APIs (Application Programming Interfaces) are sets of rules and protocols that define how software programs or devices can communicate with each other. APIs that conform to the design principles of REST, or representational state transfer, are known as REST APIs. REST APIs may also be referred to as RESTful APIs. Using RESTful APIs, developers can create requests and receive responses via an HTTP request. REST API can also be used for mapping data from a cloud platform to a data warehouse or vice versa.
As long as the data within the API is accessible to the public, it will technically not be possible to completely prevent data scraping. It is possible, however, to minimize bot activity (automated computer programs on the internet that perform certain tasks) by throttling or rare limiting. Rare limiting will be able to prevent a certain device from making an unlimited number of requests within a defined time. If too many requests are made beyond the defined limit, a 429 Too Many Attempts HTTP error is thrown. It is vital to record more than just the IP address of the device since the IP address is not unique to each device and can stop the whole network from accessing the API.
只要API中的数据对公众可访问,技术上就不可能完全阻止数据抓取。但是,可以通过限流或速率限制来最小化机器人活动(互联网上执行某些任务的自动化计算机程序)。速率限制将能够防止某个设备在定义的时间段内发出无限数量的请求。如果超出定义的限制发出过多请求,将抛出429 Too Many Attempts HTTP错误。记录不仅仅是设备的IP地址至关重要,因为IP地址并非每台设备唯一,并且可能阻止整个网络访问API。
1391. What makes MVC (Model View Controller) different from MVP (Model View Presenter)?
Developers prefer to develop Android applications by utilizing a software architecture pattern. Architecture patterns allow you to express and define a structural schema for software systems. Developers can easily maintain the software and continue to add features to the software in the future. The two most popular android architecture patterns are MVC (Model View Controller) and MVP (Model View Presenter).
MVC suggests splitting the code into three components. As soon as the developer creates a class or file for an application, he or she must categorize it into one of three layers: Model, View, and Controller. MVC建议将代码拆分为三个组件。一旦开发人员为应用程序创建了类或文件,他或她必须将其归类到三个层之一:模型、视图和控制器。
This is an architectural pattern that helps compensate for some of the shortcomings of MVC. It is composed of three components i.e., Model, View, and Presenter. 这是一种有助于弥补MVC某些缺点的架构模式。它由三个组件组成,即模型、视图和展示器。
The controller serves as a bridge between the view and model layers and therefore provides the application's user interface. As soon as the Model changes, the Controller updates the View. 控制器充当视图和模型层之间的桥梁,因此提供应用程序的用户界面。一旦模型发生变化,控制器就会更新视图。
The presenter pulls data from the model and applies the UI (user interface) logic to determine what to show. In response to the user's input notification, it manages the state of the View and takes appropriate actions. 展示器从模型中提取数据,并应用UI(用户界面)逻辑来确定要显示的内容。作为对用户输入通知的响应,它管理视图的状态并采取适当的操作。
Controllers and views have a many-to-one relationship since one Controller can select different Views depending on the operation required. 控制器和视图具有多对一关系,因为一个控制器可以根据所需操作选择不同的视图。
Presenter and View have a one-to-one relationship since the Presenter class manages only one View at a time. 展示器和视图具有一对一关系,因为展示器类一次只管理一个视图。
Support for unit testing is limited. 单元测试支持有限。
The unit testing process is highly supported. 单元测试过程得到高度支持。
1392. What do you mean by Temporal Dead Zone in ES6?
Before ES6, variable declarations were only possible using var. With ES6, we got let and const. Both let and const declarations are block-scoped, i.e., they can only be accessed within the " " surrounding them. On the other hand, var doesn't have such a restriction. Unlike var, which can be accessed before its declaration, you cannot access the let or const variables until they are initialized with some value. Temporal Dead Zone is the time from the beginning of the execution of a block in which let or const variables are declared until these variables are initialized. If anyone tries to access those variables during that zone, Javascript will always throw a reference error as given below.
console.log(varNumber); // 未定义 console.log(letNumber); // Throws the reference error letNumber is not defined console.log(letNumber); // 抛出引用错误 letNumber 未定义 var varNumber = 3; var varNumber = 3; let letNumber = 4; let letNumber = 4; Both let and const variables are in the TDZ from the moment their enclosing scope starts to the moment they are declared. let 和 const 变量从它们所在作用域开始的那一刻起,直到它们被声明的时刻,都处于 TDZ(暂时性死区)中。
1393. What do you mean by referential transparency in functional programming?
In functional programming, referential transparency is the key differentiating factor. An expression is considered referential transparent if it can be replaced or substituted with the corresponding value it computes or vice-versa without affecting the program’s result.
Example: Imagine that we have an expression called four: val four= add(1,3)
示例:假设我们有一个名为 four 的表达式:val four = add(1,3)
If four is used anywhere in our code, it can safely be replaced with add(1,3), 1 + 3 or 4 wherever it appears. Thus, all the expressions below are equivalent in meaning and output:
如果 four 在代码中的任何地方被使用,它都可以安全地被替换为 add(1,3)、1 + 3 或 4。因此,下面所有表达式在含义和输出上都是等价的:
val eight = four + four
val eight = four + four val eight_v2 = add(1,3) + add(1,3) val eight_v2 = add(1,3) + add(1,3) val eight_v3 = 4 + add(1,3) val eight_v3 = 4 + add(1,3) val eight_v4 = 8 val eight_v4 = 8 If we can swap back-and-forth between these expressions anytime, anywhere, without altering their meaning or output, then an expression is referentially transparent. 如果我们能在任何时间、任何地点在这些表达式之间来回切换,而不改变它们的含义或输出,那么这个表达式就是引用透明的。
1394. What is event bubbling and capturing in JavaScript?
The propagation of events inside the DOM (Document Object Model) is known as 'Event Flow' in JavaScript. The event flow defines the order or sequence in which a particular web page receives an event. Accordingly, event flow (propagation) in JS is dependent on the following aspects: - Event Bubbling: With Event Bubbling, the event is captured and handled first by the innermost element, and then propagates to the outermost element. Events propagate up the DOM tree from child elements until the topmost element is handled.
在 DOM(文档对象模型)中,事件的传播被称为 JavaScript 中的“事件流”。事件流定义了特定网页接收事件的顺序或次序。因此,JS 中的事件流(传播)取决于以下方面:- 事件冒泡:通过事件冒泡,事件首先被最内层元素捕获和处理,然后传播到最外层元素。事件从子元素向上传播到 DOM 树,直到最顶层元素被处理。
Event Capturing: With Event Capturing, the event is captured and handled first by the outermost element, and then propagates to the innermost element. Event cycles propagate starting with the wrapper elements and ending with the target elements that initiated the event cycle. The following diagram will help you to understand the event propagation life cycle.
下面的图示将帮助您理解事件传播的生命周期。
1395. Tell me about a project that you worked on and the technologies you used. Why did you choose them?
With this question, the interviewer can figure out the methodology of the full stack web developer and determine if he is sharp and precise in selecting the right toolset.
通过这个问题,面试官可以了解全栈开发者的方法论,并判断他在选择正确工具集时是否敏锐和精确。
While explaining the reasons for choosing a particular toolset, you should be as specific as possible. You must demonstrate that you can develop both the front and backend of the web application. Having more experience on one side of the development game than the other is okay, but you should show you are capable of handling both ends of the application.
By asking this question, the hiring manager will get an idea of the type and complexity of past projects you have completed. You should clearly state the problems you encountered and the steps you took to overcome them. In addition, you can talk about the lessons you learned from the issue.
结论 A potential employer doesn't expect applicants to know everything, whether they're freshers or experienced. However, a well-prepared and enthusiastic candidate will undoubtedly stand out. In a full stack developer interview, candidates should be able to demonstrate excellent organizational skills and precision in their work. Also, honesty and transparency pay dividends over the long run. 潜在雇主不期望申请人懂得一切,无论他们是新手还是有经验者。然而,一个准备充分且热情的候选人无疑会脱颖而出。在全栈开发者面试中,候选人应能展示出色的组织能力和工作中的精确性。此外,诚实和透明长期来看会带来回报。
In this article, we have covered the top 30+ Full-Stack developer interview questions & answers for freshers and experienced candidates so you can succeed in your next full-stack developer interview. Questions like those listed above are quick, insightful, and provide key cues that are vital to the interview process. If you review frequently asked full stack developer interview questions and answers, you increase your chances of getting hired. Make sure you review all the questions and answers.
Today, the software is rapidly created and features are often changed based on customer needs, and then it is deployed into production. Each organization has its unique way of getting new applications into the production environment. Most organizations follow the standard deployment and release strategies such as Blue-Green and Rolling Deployment. - Blue-Green Deployment Strategy:
如今,软件被快速创建,功能常根据客户需求变化,然后被部署到生产环境。每个组织有自己独特的方式将新应用带入生产环境。大多数组织遵循标准部署和发布策略,如蓝绿部署和滚动部署。- 蓝绿部署策略: A deployment strategy like this creates two separate infrastructure environments i.e., blue and green. A blue environment contains older code (old version), while a green environment (production) contains the latest code (new version). There is only one live production environment at any given time. 这种部署策略创建两个独立的基础设施环境,即蓝色和绿色。蓝色环境包含旧代码(旧版本),而绿色环境(生产)包含最新代码(新版本)。任何给定时间只有一个活跃的生产环境。
Example: For instance, the green environment is live and is receiving all user traffic, while the clone (blue) is idle. Once a new version of an application is ready for release, it can be deployed to the blue environment for testing. As soon as the new release passes testing, application traffic is switched from green to blue. Blue then becomes the live production environment, and Green becomes idle, ready for testing the next release.
Using this deployment strategy, old versions of an application are completely replaced with the new versions by completely replacing the infrastructure on which they run.
使用这种部署策略,通过完全替换应用运行的基础设施,旧版本应用被新版本完全替换。 Example: When a new version must be deployed to all nodes, the new version is deployed to the first node while all other nodes handle end-user traffic. As soon as the new version is successfully installed on the first node, it will begin managing end-user traffic while the new version is being installed on the second node. The process is repeated until all nodes have been successfully upgraded to the new version. 示例:当新版本必须部署到所有节点时,新版本部署到第一个节点,而所有其他节点处理终端用户流量。当新版本在第一个节点成功安装后,它开始管理终端用户流量,而新版本正在第二个节点安装。该过程重复,直到所有节点成功升级到新版本。
IoC (Inversion of Control), as the name suggests, is a design principle in software engineering. With IoC, different kinds of controls can be inverted in an object-oriented design to attain loose coupling. The term "controls" refers to any other responsibilities a class may have other than its primary responsibility. These include controlling the flow of an application, controlling the creation of objects, or controlling the binding and creation of dependent objects. IoC allows classes to be loosely coupled, making testing and maintenance easier.
One of the most popular tech stacks is the MEAN stack (MongoDB-ExpressJS-AngularJS-NodeJS). MEAN stack has many applications, including cloud application development. MongoDB, Express.js, AngularJS, and Node.js are among the JavaScript technologies in MEAN used to build web applications.
Definitely, it's a great career choice. Having a full-stack developer job is one of the most productive careers you can have, and its high level of responsibility makes it one of the most important careers in tech. Full-stack developers do not only specialize in front-end and back-end development but are also experts with a wide range of skill sets and knowledge. Full Stack Developers are in high demand and companies are willing to pay handsomely for those with the right skillset and diverse knowledge. Here's a Resume Sample .
A Full Stack Developer is one of the most highly paid professionals. In India, the average annual salary for a Full Stack Developer is around ₹6,66,697. With 1-4 years of experience, a full-stack developer earns an average of INR 6,53,006-10,00,000. Employees with between 5 and 9 years of experience can expect to earn between INR 12 and 17 lakhs per year. Learn More .
Ionic offers a platform service for obtaining information regarding the current device. - All of the platforms linked with the device are returned by the platform method.
It also indicates if the application is being seen on a tablet, mobile device, or browser, as well as the platform used, such as Android or iOS.
Ionic applies CSS classes to the tag when the application is loaded on the device. Ionic, for example, adds the platform-ios class to the tag on iOS devices.
1405. How can you persist data between application launches while using Ionic?
You can utilise the localStorage and sessionStorage APIs to persist data on the mobile phone because Ionic is an HTML5 framework. Because localStorage can only save strings, objects must first be stringified before they can be saved. It's also worth noting that the maximum capacity for localStorage is 5MB.
When we need to display a big amount of data in an Ionic application, the ion-infinite-scroll component comes in handy. Whenever the user scrolls a certain distance from the top or bottom of the page, this component allows information to be loaded into the app.
Every mobile application requires a technique to display a large amount of data with fewer clicks. In that instance, the infinite scroll is critical to their success. The infinite scroll component serves the same purpose that we would if we were loading ten items on a page. Whenever the user scrolls down to the bottom of those items, it triggers a new data request. This request retrieves the next set of record entries to be integrated with existing ones. This procedure continues until the new data is no longer visible in chunks as the user scrolls. The news feed region of Facebook, Instagram, or Twitter is the finest example of an ion-infinite-scroll. When you reach the desired distance, the page automatically loads fresh posts, and a loading spinner appears at the bottom of the screen.
The @ionic/storage package in the ionic framework has a storage module. We may use the storage module to hold key-value pairs and JSON objects in a safe and reliable manner. It has its own set of constraints.
Storage engines come in a variety of flavours, and which one is ideal for you depends on the platform you're using. When executing in a native application context, SQLite is used for storage. Storage will use IndexedDB, WebSQL, and localstorage while operating on the web or as a Progressive Web App. The SQLite file-based database is the most stable and widely used, avoiding the drawbacks of alternative storage engines such as IndexedDB, WebSQL, and localstorage.
The following methods can be used to minimise the size of an Ionic app: - First, compress all of the relevant icons and images, then eliminate any that you don't want.
Second, minify all JS and CSS files and make the necessary changes to the index.html page.
Third, get rid of any unnecessary external modules or Cordova plugins that aren't in use. You can also eliminate unneeded code from the programme, which will save you a lot of space.
Finally, you can use the following command to shrink the app's size: ionic build android -prod.
1409. What is the ion-refresher component's purpose in Ionic?
The term "refreshing" refers to the process of updating the currently displayed page so that the user may see the most recent content. To provide pull-to-refresh capabilities to a content component, Ionic provides the ion-refresher component. Ionic allows users to utilise touch to pull the page down from the top of a list of data to access more information. During the refresher's output events, the updated data should be adjusted. When the page has finished refreshing, execute the refresher's complete() function.
Because Ionic is built on ES6 and TypeScript, your editors or IDE must be capable of supporting these new languages. The most common editors and integrated development environments (IDEs) for Ionic application development are: - Visual Studio
因为 Ionic 基于 ES6 和 TypeScript 构建,你的编辑器或 IDE 必须能够支持这些新语言。用于 Ionic 应用开发的最常见编辑器和集成开发环境(IDE)包括:- Visual Studio
WebStorm
Atom
ALM (Application Lifecycle Management)
Angular IDE by Webclipse.
1411. How can native phone functionality, such as the camera, be accessed in Ionic applications?
Ionic doesn't have a camera API by default. We may utilise Cordova plugins in our application because Ionic has a plugins architecture that is based on Cordova. The Ionic team has created a collection of Cordova extensions that include Angular wrappers, which can be obtained at ngCordova.
To use Cordova plugins, we must use the Ionic command install to install the plugin. In some circumstances, the plugin's Angular module will also need to be added to your Angular application. We can use cordova-plugin-camera, which is accessible on GitHub, to contact the camera API to use a mobile phone's camera in an Ionic application. This plugin creates a global navigator.camera object with an API for taking photos and selecting images from the system's image library.
Debugging is an important element of any development process. When it comes to Ionic, We can use Chrome or Safari to debug Android and iOS applications.
ionic Cordova can be used to execute the application on a real device. Run Android or ionic Cordova build Android to build the apk and transfer it to the phone.
Connect your device to your computer using a USB cable, then open Google Chrome and go to chrome:/inspect/#devices to see your phone and application name. There's an inspect button there.
You'll be able to inspect the application and look at the logs now. iOS: To debug an iOS application in real-time, follow the steps below. - Execute the command ionic Cordova to run the application on the device. Build the application with ionic Cordova or run-ios To get the application on the phone, you'll need to build it on iOS and use Xcode.
Ionic Market is a marketplace for Ionic developers who want to use pre-built starters, themes, plugins, and other resources. Starters, Plugins, and Themes are the three sorts of items available on the Ionic Market. The Ionic marketplace makes it simple to submit, buy, and download starters, plugins, and themes for your projects. It's a good site to sell and buy ionic items.
The Ionic Market is completely free to use, and there are no additional fees for these bespoke services. If you placed your add-on for sales in the Ionic Market, anyone may sell it directly via the market or refer to another marketplace.
Ionic makes advantage of the Angular life-cycle events. These are the life-cycle events: - ngOnInit: It is a one-time event that occurs during component initialization. It can be used to set up local members and make one-time calls to services.
ngOnDestroy: This event is triggered shortly before the view is destroyed by Angular. It's useful for things like unsubscribing from observables and cleaning up.
ionViewWillEnter: When the component routing-to is going to animate into view, ionViewWillEnter is invoked.
ionViewDidEnter: When the component routing-to has done animating, ionViewDidEnter is fired.
ionViewWillLeave: When the component routing-from is about to animate, it fires the ionViewWillLeave event.
ionViewDidLeave: When the component routing-to has done animating, it fires the ionViewDidLeave event.
There are a few more lifecycle events that would prohibit users from gaining unwanted access. - ionViewCanEnter: It is called before entering a view, lets you control whether or not the view can be managed by the user.
ionViewCanLeave: This feature is activated before the user can leave a view and allows you to control whether the view can be left or not. Routing Guards can be used to replace the above two events in Ionic 4.
在 Ionic 4 中,路由守卫可用于替代上述两个事件。
1415. In Ionic 4, name all of the page life-cycle hooks.
A splash screen looks like a start screen or a start-up screen. It's a graphical control element that includes an image, a logo, and the software's current version. The splash screen is simply a display screen that allows people to look at something while the hardware is loading so that software may be presented to them. It commonly displays as a game or software begins to load.
Ionic Events is a publish-subscribe event system that may be used to send messages across multiple components and pages. To put it another way, it's a framework for transmitting and responding to app-level events across your entire app. Interactivity with users can be added via a variety of Ionic events. All of the Ionic events are explained in the table below.
An alert is a dialog that provides crucial information to the user in order for them to make a decision or allows them to select a specific action or a set of actions. Before resuming contact with the application, the user can dismiss it manually. It's a floating modal that should be used for short responses like password verification and minor application notifications, among other things.
In an Ionic application, the alert controller is in charge of creating an alert. It creates an alert using the create() method, which can be customised by giving the alert option to the create() method.
A capacitor is a cross-platform software that allows you to create web applications that work natively on iOS, Android, Electron, and the Web using a single code base. These applications are known as Native Progressive Web applications, and they are the next development after Hybrid applications.
It is intended to be a successor for Apache Cordova and Adobe Phonegap, drawing influence from other successful cross-platform technologies such as React native, but it is only focused on allowing modern web applications to operate on all major web platforms. Many existing Cordova plugins are supported by the capacitor in a backwards-compatible manner.
Capacitor converts your web application into a platform-specific native binary. As a result, you'll spend a lot of time establishing and then building a mobile-friendly web app. Using Capacitor's plugins (such as Camera) or existing Cordova plugins with Capacitor's Cordova Compatibility, you'll communicate with the native platform underneath. Capacitor or Cordova plugins are used to interact between the Web View and the native app. Plugins provide your web application access to native APIs like the camera, geolocation, and filesystem. The capacitor includes a number of JavaScript utilities that can help you make sure your apps operate on many platforms with the same codebase. To utilise them, first import Capacitor, then call the utility function you want.
1420. How is the performance of an Ionic application on older Android devices?
Ionic Applications give iOS and Android devices incredible stability. It has excellent performance, little maintenance, and requires less storage space to run new Ionic applications, among other benefits. However, it has been noted that the Ionic Application does not run smoothly on older Android smartphones. In older Android devices, any application built using the Ionic framework has been reported as non-working. Any Ionic application running on Android devices prior to version 5 has a number of difficulties, including low performance/non-performance, heavy maintenance, interfering with other applications, and so on. A crosswalk plugin must be created externally to run applications on older Android devices, which will help Ionic applications perform better on older Android smartphones.
Views are cached by default to increase efficiency. The element of a view is left in the DOM when it is navigated away from it, and its scope is separated from the $watch cycle. When you navigate to a previously cached view, its scope is reconnected, and the existing element in the DOM becomes the current view. This also allows prior views' scroll positions to be preserved.
Caching can be turned on and off in a variety of ways. Ionic caches a maximum of 10 views by default, and not only can this be changed, but applications can also specify which views should and should not be cached explicitly. Caching can be turned off per view by setting cache: false in the state settings of the UI router. The$ionicConfigProvider may be used to specify the maximum number of cached views, but it can also be used to turn off all caching by setting it to 0.
Ionic Native is a TypeScript wrapper for Cordova or PhoneGap plugins that allows you to integrate any native feature into your Ionic project. With the help of Ionic Native, we can quickly integrate any of the Cordova plugin communities into an Ionic application. One of the benefits of being an Ionic native is that you can create better code. We can also utilise Cordova plugins without Ionic Native, but Ionic Native adds types to these Cordova plugins via wrapper classes, allowing us to employ IntelliSense and code suggestions. This keeps you from making mistakes and allows you to develop codes faster and more effectively. The Ionic Native directory is regularly updated with new plugins.
Security is a typical concern while developing hybrid applications, as long as your application can be reverse-engineered. - Ionic CLI has had built-in code uglification since version 4, which is a typical approach for making code difficult to read by hackers. However, you should be aware that there is no code uglification when using Angular CLI or previous versions of Ionic. Your programmers will have to uglify the code themselves.
A man-in-the-middle attack is one of several ways to compromise what's going on with your mobile application or PWA. What difference does it make? Because, in essence, your Ionic application is a web page that runs on the device. The crucial point to remember is that Ionic connects with the backend via standard HTTP calls. As a result, you'll want to apply the same security protections to your Ionic application that you do to your website, such as using HTTPS instead of HTTP.
Developers can include custom or user-provided content in components like ion-alert. This content, which can be plain text or HTML, should be regarded as untrustworthy. Before doing anything else with any untrusted information, it's critical to sanitise it. Using innerHTML without sanitization, for instance, presents an attack vector for bad actors to insert malicious material and potentially conduct a Cross-Site Scripting attack (XSS). Ionic includes basic sanitization methods for the components it offers, but it is up to the developer to ensure that all data is sanitised for user-created components.
If an attacker finds a flaw in an application's code (for instance, a third-party API call or a JavaScript package), they may find a way to exploit it such that malicious code is executed instead. The Content Security Policy (CSP) meta tag was created to aid in the prevention of such attacks by specifying which network requests are permitted and where assets are loaded from. You'll observe that Ionic apps for iOS and Android often use Cordova's Network Whitelist Plugin to protect webviews that don't support CSP from cross-site scripting.
1424. What does it imply that Ionic has become framework-agnostic?
Ionic has been reliant on Angular framework components since its inception as a utility for Angular users. Ionic became framework-agnostic in version 4, which means it is no longer dependent on Angular. The move was made possible through the use of web components and the promotion of Ionic's command-line interface.
Web components are a collection of features that make use of common APIs that are natively supported by practically all mobile browsers today. As a result, they may be deployed on any mobile device or utilised to develop desktop applications using the Electron framework, such as Progressive Web applications (PWAs). The use of web components with Ionic also allows for the use of any framework.
1425. How do you prevent two network calls if multiple components are attempting to make an HTTP call to the same URL?
Network calls are one of the key areas that will have a significant impact on the app's performance. To improve the app's performance, it should be fine-tuned to the highest level of accuracy. - If two different components are attempting to make HTTP calls to the same URL, it is preferable to make a single call and transmit data to both components than to make two separate HTTP calls. The requested action is completed in a matter of seconds.
The best method to do this is to use a root component. A shared root component should be used by all components making HTTP calls. This keeps note of URLs that were requested a few seconds ago, and if they are requested again, it can add a small delay before sending the result to both components.
1426. What is the difference between AOT (Ahead of Time Compiler) and JIT (Just In Time Compiler), and which one is employed by Ionic?
Because Ionic 1-3 is heavily reliant on Angular. The same compiling options that were available for Angular were also accessible for Ionic. - JIT is an abbreviation for "just in time compiler". It is a sort of compilation in which the application is compiled in the browser at runtime.
AOT is an abbreviation for "ahead of time compiler”. It is a sort of compilation in which the application is compiled in the build time.
It will be JIT if we only use the ionic Cordova build platform (android or iOS). It will use AOT if we use the prod flag, Ionic Cordova builds platform --prod. When compared to AOT, software designed with JIT is slower. However, AOT requires greater compilation time than JIT. So utilise JIT for quick checks and AOT for final deployment.
结论: In the mobile development market, Ionic developers are in high demand. Prepare with these Ionic framework interview questions to ace your next Ionic interview and pursue a career as a Mobile Application Developer, Frontend Developer, and, of course, an Ionic developer. We are certain that this article on Ionic interview questions has significantly increased your understanding of Ionic concepts. You will be able to confidently crack any relevant interview if you have a firm grasp of all of the questions presented here. Answering questions about Ionic CLI, distinct components in Ionic, and how to establish a new project using Ionic CLI will be easier if you study these Ionic framework interview questions and answers well. 在移动开发市场中,Ionic 开发人员需求很高。通过这些问题为你的下一次 Ionic 面试做好准备,并追求移动应用开发人员、前端开发人员以及当然是 Ionic 开发人员的职业。我们确信这篇关于 Ionic 面试问题的文章显著提高了你对 Ionic 概念的理解。如果你对这里所有问题有扎实的掌握,你将能自信地应对任何相关面试。如果你认真学习这些 Ionic 框架面试问题和答案,回答有关 Ionic CLI、Ionic 中的不同组件以及如何使用 Ionic CLI 建立新项目的问题会更容易。
Since the 1990s, Objective-C has been used by Apple as an object-oriented programming language. This language combines the advantages of two earlier languages - C and Smalltalk. As a superset of C, it provides object-oriented functionality and a dynamic runtime environment.
Following are data types that the developers mostly use in Objective – C: - BOOL: Represents a Boolean value that is either true or false. Both the _Bool or BOOL keywords is valid.
以下是开发人员在Objective-C中最常使用的数据类型:- BOOL:表示一个布尔值,要么为真要么为假。_Bool或BOOL关键字都是有效的。 Example:_Bool flag = 0;BOOL secondflag = 1; - NSInteger: Represents an Integer. 示例:_Bool标志 = 0;BOOL第二标志 = 1; - NSInteger:表示一个整数。 Example:typedef long NSInteger;typedef int NSInteger; - NSUInteger: Represents an unsigned integer. 示例:typedef long NSInteger;typedef int NSInteger; - NSUInteger:表示一个无符号整数。 Example:typedef unsigned long NSUInteger; typedef unsigned int NSUInteger; - NSString: Represents a string. 示例:typedef unsigned long NSUInteger;typedef unsigned int NSUInteger; - NSString:表示一个字符串。 Example:NSString *greeting = @"Hello"; 示例:NSString *greeting = @"Hello";
Swift is the fastest-growing programming language today, created by Apple. With a significant advantage pool over the well-known Objective-C, Swift holds a leading position in iOS development. It's an entirely new language created specifically to develop software for Apple's operating systems. Since Swift implements all the features of other modern languages, you can find type inference, optional, generics, and such higher-order functions. It is compatible with macOS, iOS, watchOS, and tvOS.
Swift programming language is being designed so that developers can write correct programs and maintain them easily. It offers the following features: - Safety: Swift is an efficient way to write programs. Checking code before it is used in production is very important. Apple Swift removes any unsafe code before it is used in production.
Simple syntax: Swift's syntax is simple and easy-to-use, just as developers would expect it. The syntax features of Swift enable you to write more expressive code.
Readability: Swift has a simple syntax, which is easier to read and write. It is easier for developers to write Swift code since it is more similar to plain English, enabling them to spend less time looking for problematic code.
Multiplatform support: Swift is fully compatible with iOS, macOS, tvOS, watchOS, Linux, and many other platforms. This means you are able to develop software that is compatible with all operating systems.
Open-source: Swift is developed at swift.org, an open-source framework. For Swift to become a defining programming language, the technology had to be open to all. Swift supports all Apple platforms and makes programming easier, faster, and safer.
Compatible with Objective C: Swift has full compatibility with Objective-C. Swift enables programmers to import frameworks from Objective-C using the Swift syntax. Programmers can utilize Objective-C libraries and classes inside Swift code.
Information about an error condition is encapsulated within an NSError object in an extendable and object-oriented manner. An NSError object is comprised of three basic attributes: a predefined error domain (represented as a string), a domain-specific error code, and a user info dictionary containing application-specific information.
The term enumeration refers to a user-defined data type consisting of a set of related values that allows you to work with those values in your code in a type-safe manner. An enumerated data type is defined by the keyword enum.
enum enum_name { // enumeration values are described here // 此处描述枚举值 } Example: 示例:
enum MonthsofaYear
enum MonthsofaYear { case January case January case Februrary case Februrary … case December case December } Values defined in an enumeration MonthsofaYear such as January, February, and so on until December are its enumeration cases. New enumeration cases can be introduced using the case keyword. You can put multiple cases on a single line, separated by commas as follows: 在枚举 MonthsofaYear 中定义的值,如 January、February 等直到 December,都是其枚举成员。可以使用 case 关键字引入新的枚举成员。你也可以将多个成员放在同一行,用逗号分隔,如下所示:
enum MonthsofaYear
enum MonthsofaYear { case January, February,....,December case January, February,....,December }
Lazy properties are properties whose initial value isn't computed until the first time they are used. Including the lazy modifier/keyword before the declaration of a stored property indicates it is lazy. This lets you delay the initialization of stored properties. This could be a great way to streamline your code and reduce unnecessary work. When a code is expensive and unlikely to be called consistently, a lazy variable can be a great solution.
class Person { var name: String var name: String lazy var personalizdgreeting : String = { lazy var personalizdgreeting : String = { return “HelloScala (self.name)!” return “HelloScala (self.name)!” }() init(name: String) { init(name: String) { self.name = name self.name = name } } As shown above, we aren't sure what value personalizedgreeting should have. To know the correct greeting for this person, we need to wait until this object is initialized. 如上所示,我们不确定 personalizedgreeting 应该具有什么值。要知道这个人的正确问候语,我们需要等到这个对象被初始化。
1434. What are generics in swift and write its usage?
A major feature of Swift is generics, and much of the Swift standard library is written in generic code. Swift's 'Array' and 'Dictionary' types, for example, constitute generic collections. Generic code allows you to create flexible, reusable functions and types that work with any data type. You can create code that does not get too specific about underlying data types, resulting in cleaner code.
Swift 的一个主要特性是泛型,而且 Swift 标准库的大部分都是用泛型代码编写的。例如,Swift 的 'Array' 和 'Dictionary' 类型构成泛型集合。泛型代码允许你创建灵活、可重用的函数和类型,适用于任何数据类型。你可以创建不过分涉及底层数据类型的代码,从而使代码更简洁。
Example:
示例:
func Swapping(x: inout Int, y: inout Int)
func Swapping(x: inout Int, y: inout Int) { let temp = x let temp = x x = y x = y y = temp y = temp } var num1 = 10 var num1 = 10 var num2 = 50 var num2 = 50 print("Before Swapping: (num1) and (num2)") print("交换前:(num1) 和 (num2)") Swapping(x: &num1, y: &num2) Swapping(x: &num1, y: &num2) print("After Swapping: (num1) and (num2)") print("交换后:(num1) 和 (num2)") Output: 输出:
Before Swapping: 10 and 50
交换前:10 和 50 After Swapping: 50 and 10 交换后:50 和 10 In the above example, we have defined a function called Swapping() to swap integers. It takes two parameters x and y of int type. As seen in the output, the values of x and y are exchanged after the swapping. 在上面的示例中,我们定义了一个名为 Swapping() 的函数来交换整数。它接受两个 int 类型的参数 x 和 y。从输出可以看出,交换后 x 和 y 的值发生了变换。
Swift programming defines a dictionary as an unordered collection of items. It stores items in key-value pairs. A dictionary uses a unique identifier called a key to store an associated value which can later be referenced and retrieved through the same key.
["Rahul": "79", "Aditya": "86", "Aditi": "67"] In the above example, we have created a dictionary named examresult. Here, - Keys are "Rahul", "Aditya", "Aditi" 在上述示例中,我们创建了一个名为examresult的字典。这里,- 键是"Rahul"、"Aditya"、"Aditi"
Values are "79", "86", "67"
1436. Why design patterns are important? Name some of the popular design patterns used in iOS?
A design pattern is a solution to a specific problem you might encounter while designing an app's architecture. They are templates designed to make coding easier and more reusable for you. Following are some of the design patterns that can be used in iOS:
MVC (Model-View-Controller): MVC is a design pattern for developing web applications in which three components are connected i.e., view, controller, and model. Views can be conceived as the user interface shown to the end-user at a certain point in time. The model represents the data to be shown on the view. The controller acts as a link between view and model. There is always a relationship between these three components.
MVVM ( Model-View-View Model): Unlike MVM, there is a special layer in MVVM called the View Model between the View and the Model. Using a view model, model information can be transformed into values that can be displayed on the view. There is a binding link between the view and View model that allows the view model to share updates with the view.
Facade: The facade design pattern provides a simplified (but limited) interface to a complex set of classes, libraries or frameworks. As opposed to providing the user with a set of classes and their APIs, you instead provide a simple, unified API. While Facade helps to reduce overall application complexity, it also helps to move unwanted dependencies to a single location.
iOS supports the SBJson framework as the JSON framework. Humans and computers alike can easily read and write this lightweight data exchange formatter. JSON handling is simplified with SBJson's flexible APIs and additional control.
iBeacon, Apple's new low-energy Bluetooth wireless technology, allows iPhone and other iOS users to receive location-based information and services on smartphones. IBeacons are small, wireless transmitters that transmit signals to nearby smart devices via Bluetooth low energy technology.
KVC (Key-Value Coding): It enables object properties to be accessed at runtime using strings rather than knowing the property names statically during development.
KVC(键值编码):它使得对象属性可以在运行时通过字符串访问,而不必在开发期间静态地知道属性名称。
KVO (Key-Value Observing): In Objective-C and Swift, KVO is one of the methods for observing program state changes. If an object has instance variables, KVO enables other objects to observe the changes to those variables.
Software developers can use testing-driven development (TDD) in the development of software. In TDD, developers plan the features of the software that they want to create and then write test cases for each feature before implementing it. Through test-driven development, we can gain insight into both the quality of the implementation (does it work) and the quality of the design (is it well structured).
At first, the test case will fail because the code is not yet implemented, and this is usually referred to as the red phase. After that, code is written to ensure that the test case passes and does not break any components or current test cases, which is called the green phase. The developer should then refactor the implementation of the code by cleaning and maintaining the codebase, as well as optimizing the efficiency. This process should then be repeated every time a new test case is added.
Completion handlers are basically just functions passed as parameters to other functions. They are used to dealing with the response of asynchronous tasks since we do not know when they will end. Completion handlers inform an application when an operation, such as an API call, has been completed. The program is informed that the next step needs to be executed.
Let's create a simple class called CompletionHandler that has one method called count that counts from 0 to 50. Once it reaches 25 (a random value), it will make a network request to https://scaler.com. Once the request has been completed, we will print Received response.
class CompletionHandler { func count() { func count() { for i in 0...50 { for i in 0...50 { if i == 25 { if i == 25 { if let url = URL(string: "https://scaler.com") { if let url = URL(string: "https://scaler.com") { URLSession.shared.dataTask(with: url) { (data, response, error) in URLSession.shared.dataTask(with: url) { (data, response, error) in print("Received response") print("Received response") }.resume() }.resume() } } print("I = ", i) 打印("I = ", i) } } } let newInstance = CompletionHandler() 让 newInstance = CompletionHandler() newInstance.count() newInstance.count() You will see all the numbers printed out in the console as soon as the code runs, but the Received response will be printed only after all those other numbers have been printed. 代码运行后,你会立刻在控制台中看到所有数字被打印出来,但“收到响应”这一信息只有在其他所有数字都打印完成后才会显示。
1442. State the difference between strong, weak, read only and copy.
The difference between strong, weak, read-only and copy is as follows: - Strong: This property maintains a reference to property throughout the lifetime of an object. When you declare strong, you intend to "own" the object you are referencing. Data you assign to this property will not be destroyed as long as you or any other object references it strongly.
Weak: It means that the object should be kept in memory as long as someone points to it strongly, and you don't need control over its lifetime.
Read-only: An object's property can be defined initially, but it cannot be altered or modified.
Copy: This attribute is an alternative to strong. In place of taking ownership of a current object, it creates a copy of whatever you assign to the property, then takes ownership of that copy.
In simple terms, dynamic dispatch means that the program decides at runtime which implementation of a particular method or function it needs to invoke. In the case where a subclass overrides a method of its superclass, dynamic dispatch determines whether to invoke the subclass implementation of the method or the parents.
@synthesize: This command generates getter and setter methods within the property and works in conjunction with the @dynamic command. By default, @synthesize creates a variable with the same name as the target of set/get as shown in the below example.
Example1:@property (nonatomic, retain) NSButton *someButton;...@synthesize someButton;It is also possible to specify a member variable as its set / get target as shown below:
示例1:@property (nonatomic, retain) NSButton *someButton;...@synthesize someButton;也可以指定一个成员变量作为其设置/获取目标,如下所示: Example2:@property (nonatomic, retain) NSButton *someButton;...@synthesize someButton= _homeButton;Here, the set / get method points to the member variable _homeButton. - @dynamic: This tells the compiler that the getter and setter methods are not implemented within the class itself, but elsewhere (like the superclass or that they will be available at runtime). 示例2:@property (nonatomic, retain) NSButton *someButton;...@synthesize someButton= _homeButton;这里,设置/获取方法指向成员变量_homeButton。- @dynamic:这告诉编译器getter和setter方法不是在该类本身中实现的,而是在其他地方(如父类或将在运行时可用)。 Example:@property (nonatomic, retain) IBOutlet NSButton *someButton;...@dynamic someButton; 示例:@property (nonatomic, retain) IBOutlet NSButton *someButton;...@dynamic someButton;
1445. How can you implement storage and persistence in iOS?
Persistence means storing data on the disk so that it can be retrieved without being altered the next time the app is opened. From simple to complex, there are the following methods for storing data: - Data structures such as arrays, dictionaries, sets, and other data structures are perfect for storing data intermediately.
Apple's iOS supports both synchronous and asynchronous tasks. In synchronous operations, tasks are performed one at a time. Therefore, other tasks must wait until the previous task is completed before continuing. Asynchronous tasks run simultaneously in the background. If background tasks are completed, you will be notified. Asynchronous programming allows you to process multiple requests at the same time, so you can accomplish more tasks in a shorter amount of time.
The figure clearly indicates that synchronous tasks take more time to complete, i.e. 45 seconds since each task is performed one at a time. Asynchronous tasks, on the other hand, take less time to complete i.e. 20 seconds as they run simultaneously.
结论 Multibillions of Apple devices are in use worldwide. The number of iOS users worldwide has been rising steadily, which bodes well for iOS app developers. If you are seeking to make a career in iOS application development , then InterviewBit is the ideal platform to start with. In this article, we have put together 35+ of the most commonly asked iOS interview questions to help you succeed at your iOS job interview. iOS developers also need to stay apprised of changes in the iOS community. Make sure you read Apple developer news, listen to podcasts and read blogs as well. This is likely not to be a question in an interview, but it makes you stand out. 全球有数十亿台苹果设备在使用中。全球iOS用户数量持续稳步增长,这对iOS应用开发者来说是个好兆头。如果你有志于在iOS应用开发领域发展职业,那么InterviewBit是理想的起点平台。在本文中,我们整理了35个以上最常见的iOS面试问题,帮助你成功通过iOS工作面试。iOS开发者还需要及时了解iOS社区的变化。确保你阅读苹果开发者新闻,收听播客并阅读博客。这虽然不太可能成为面试中的问题,但能让你脱颖而出。
Hopefully, these answers will be helpful in better understanding iOS basics, Swift, and advanced topics. Anyone looking to succeed in an iOS interview would benefit from knowing the answers to these Swift and iOS developer interview questions. Good luck with your interview!
Arrow functions were introduced in the ES6 version of javascript. They provide us with a new and shorter syntax for declaring functions. Arrow functions can only be used as a function expression. Let’s compare the normal function declaration and the arrow function declaration in detail:
// 传统函数表达式 var add = function(a,b){ var add = function(a,b){ return a + b; return a + b; }
// Arrow Function Expression
// 箭头函数表达式 var arrowAdd = (a,b) => a + b; var arrowAdd = (a,b) => a + b; Arrow functions are declared without the function keyword. If there is only one returning expression then we don’t need to use the return keyword as well in an arrow function as shown in the example above. Also, for functions having just one line of code, curly braces can be omitted. 箭头函数在声明时不需要使用function关键字。如果只有一个返回表达式,那么也无需在箭头函数中使用return关键字,如上述示例所示。此外,对于只有一行代码的函数,可以省略花括号。
// Traditional function expression
// 传统函数表达式 var multiplyBy2 = function(num){ var multiplyBy2 = function(num){ return num * 2; return num * 2; } // Arrow function expression // 箭头函数表达式 var arrowMultiplyBy2 = num => num * 2; var arrowMultiplyBy2 = num => num * 2; If the function takes in only one argument, then the parenthesis () around the parameter can be omitted as shown in the code above. 如果函数只接受一个参数,那么可以省略参数周围的圆括号(),如上述代码所示。
obj1.valueOfThis(); // Will return the object obj1
obj1.valueOfThis(); // 将返回对象obj1 obj2.valueOfThis(); // Will return window/global object obj2.valueOfThis(); // 将返回 window/全局对象 The biggest difference between the traditional function expression and the arrow function is the handling of this keyword. By general definition, this keyword always refers to the object that is calling the function. As you can see in the code above, obj1.valueOfThis() returns obj1 since this keyword refers to the object calling the function. 传统函数表达式与箭头函数最大的区别在于对 this 关键字的处理。根据一般定义,this 关键字始终指向调用该函数的对象。正如上面代码所示,obj1.valueOfThis() 返回 obj1,因为 this 关键字指向调用函数的对象。
In the arrow functions, there is no binding of this keyword. This keyword inside an arrow function does not refer to the object calling it. It rather inherits its value from the parent scope which is the window object in this case. Therefore, in the code above, obj2.valueOfThis() returns the window object.
在箭头函数中,没有 this 关键字的绑定。箭头函数内部的 this 关键字并不指向调用它的对象,而是继承自父作用域的值,在这种情况下即 window 对象。因此,在上面的代码中,obj2.valueOfThis() 返回 window 对象。
The Prototype Pattern produces different objects, but instead of returning uninitialized objects, it produces objects that have values replicated from a template – or sample – object. Also known as the Properties pattern, the Prototype pattern is used to create prototypes.
The introduction of business objects with parameters that match the database's default settings is a good example of where the Prototype pattern comes in handy. The default settings for a newly generated business object are stored in the prototype object.
The Prototype pattern is hardly used in traditional languages, however, it is used in the development of new objects and templates in JavaScript, which is a prototypal language.
Before the ES6 version of javascript, only the keyword var was used to declare variables. With the ES6 Version, keywords let and const were introduced to declare variables.
在 JavaScript 的 ES6 版本之前,只有关键字 var 用于声明变量。随着 ES6 版本的到来,引入了关键字 let 和 const 来声明变量。
keyword 关键字
const
let
var
global scope 全局作用域
no 否
no 否
yes 是
function scope 函数作用域
yes 是
yes 是
yes 是
block scope 块级作用域
yes 是
yes 是
no 否
can be reassigned 可重新赋值
no 否
yes 是
yes 是
Let’s understand the differences with examples:
让我们通过示例来理解这些区别:
var variable1 = 23;
var variable1 = 23;
let variable2 = 89;
let variable2 = 89;
function catchValues(){
function catchValues(){ console.log(variable1); console.log(variable1); console.log(variable2); console.log(variable2);
// Both the variables can be accessed anywhere since they are declared in the global scope
// 因为这两个变量都是在全局作用域中声明的,所以它们可以在任何地方被访问 }
window.variable1; // Returns the value 23
window.variable1; // 返回数值 23
window.variable2; // Returns undefined
window.variable2; // 返回 undefined
The variables declared with the let keyword in the global scope behave just like the variable declared with the var keyword in the global scope.
Variables declared in the global scope with var and let keywords can be accessed from anywhere in the code.
But, there is one difference! Variables that are declared with the var keyword in the global scope are added to the window/global object. Therefore, they can be accessed using window.variableName.Whereas, the variables declared with the let keyword are not added to the global object, therefore, trying to access such variables using window.variableName results in an error.
var vs let in functional scope
函数作用域中的 var 与 let 对比 function varVsLetFunction(){ function varVsLetFunction(){ let awesomeCar1 = "Audi"; let awesomeCar1 = "Audi"; var awesomeCar2 = "Mercedes"; var awesomeCar2 = "Mercedes"; }
console.log(awesomeCar1); // Throws an error
console.log(awesomeCar1); // 抛出错误 console.log(awesomeCar2); // Throws an error console.log(awesomeCar2); // 抛出错误 Variables are declared in a functional/local scope using var and let keywords behave exactly the same, meaning, they cannot be accessed from outside of the scope. 在函数/局部作用域中使用 var 和 let 关键字声明的变量行为完全相同,即它们不能被从该作用域外部访问。
{ var variable3 = [1, 2, 3, 4];
var variable3 = [1, 2, 3, 4]; }
console.log(variable3); // Outputs [1,2,3,4]
console.log(variable3); // 输出 [1,2,3,4]
{ let variable4 = [6, 55, -1, 2];
let variable4 = [6, 55, -1, 2]; }
console.log(variable4); // Throws error
console.log(variable4); // 抛出错误
for(let i = 0; i < 2; i++){
for(let i = 0; i < 2; i++){ //Do something // 执行某些操作 }
In javascript, a block means the code written inside the curly braces {}.
Variables declared with var keyword do not have block scope. It means a variable declared in block scope {} with the var keyword is the same as declaring the variable in the global scope.
Variables declared with let keyword inside the block scope cannot be accessed from outside of the block.
Const keyword
常量关键字
Variables with the const keyword behave exactly like a variable declared with the let keyword with only one difference, any variable declared with the const keyword cannot be reassigned.
Example:
const x = {name:"Vivek"};
const x = {name:"Vivek"};
x = {address: "India"}; // Throws an error
x = {address: "India"}; // 抛出错误
x.name = "Nikhil"; // No error is thrown
x.name = "Nikhil"; // 不会抛出错误
const y = 23;
const y = 23;
y = 44; // Throws an error
y = 44; // 抛出错误 In the code above, although we can change the value of a property inside the variable declared with const keyword, we cannot completely reassign the variable itself. 在上面的代码中,虽然我们可以改变用 const 关键字声明的变量中属性的值,但不能完全重新赋值该变量本身。
1450. What is the rest parameter and spread operator?
Both rest parameter and spread operator were introduced in the ES6 version of javascript. Rest parameter ( … ): - It provides an improved way of handling the parameters of a function.
**Note- Rest parameter should always be used at the last parameter of a function:
**注意:剩余参数应始终用作函数的最后一个参数:
// Incorrect way to use rest parameter
// 不正确的剩余参数使用方式 function randomFunc(a,...args,c){ function randomFunc(a,...args,c){ //Do something // 执行某些操作 }
// Correct way to use rest parameter
// 正确的剩余参数使用方式 function randomFunc2(a,b,...args){ function randomFunc2(a,b,...args){ //Do something // 执行某些操作 }
Spread operator (…): Although the syntax of the spread operator is exactly the same as the rest parameter, the spread operator is used to spreading an array, and object literals. We also use spread operators where one or more arguments are expected in a function call.
let array1 = [3, 4, 5, 6]; let clonedArray1 = [...array1]; let clonedArray1 = [...array1]; // Spreads the array into 3,4,5,6 // 将数组展开为 3,4,5,6 console.log(clonedArray1); // Outputs [3,4,5,6] console.log(clonedArray1); // 输出 [3,4,5,6]
let obj1 = {x:'Hello', y:'Bye'};
let obj1 = {x:'Hello', y:'Bye'}; let clonedObj1 = {...obj1}; // Spreads and clones obj1 let clonedObj1 = {...obj1}; // 展开并克隆 obj1 console.log(obj1); console.log(obj1);
let obj2 = {z:'Yes', a:'No'};
let obj2 = {z:'Yes', a:'No'}; let mergedObj = {...obj1, ...obj2}; // Spreads both the objects and merges it let mergedObj = {...obj1, ...obj2}; // 展开两个对象并合并 console.log(mergedObj); console.log(mergedObj); // Outputs {x:'Hello', y:'Bye',z:'Yes',a:'No'}; // 输出 {x:'Hello', y:'Bye',z:'Yes',a:'No'}; *Note- Key differences between rest parameter and spread operator: *注意:rest 参数和展开运算符之间的关键区别: Rest parameter is used to take a variable number of arguments and turns them into an array while the spread operator takes an array or an object and spreads it Rest parameter is used in function declaration whereas the spread operator is used in function calls. 剩余参数用于函数声明,而展开运算符用于函数调用。
1451. In JavaScript, how many different methods can you make an object?
Promises are used to handle asynchronous operations in javascript. Before promises, callbacks were used to handle asynchronous operations. But due to the limited functionality of callbacks, using multiple callbacks to handle asynchronous code can lead to unmanageable code. Promise object has four states - - Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed.
Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
Settled - This state represents that the promise has been either rejected or fulfilled. A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively.
resolve is a function that will be called when the async operation has been successfully completed. reject is a function that will be called, when the async operation fails or if some error occurs. Example of a promise: Promises are used to handle asynchronous operations like server requests, for ease of understanding, we are using an operation to calculate the sum of three elements. In the function below, we are returning a promise inside a function:
function sumOfThreeElements(...elements){ return new Promise((resolve,reject)=>{ 返回一个全新的Promise((resolve,reject)=>{ if(elements.length > 3 ){ 如果(elements.length > 3 ){ reject("Only three elements or less are allowed"); reject("只允许三个或更少的元素"); } else{ 否则{ let sum = 0; 让 sum = 0; let i = 0; 让 i = 0; while(i < elements.length){ 当(i < elements.length){ sum += elements[i]; sum += elements[i]; i++; i++; } resolve("Sum has been calculated: "+sum); resolve("总和已计算:"+sum); } }) } In the code above, we are calculating the sum of three elements, if the length of the elements array is more than 3, a promise is rejected, or else the promise is resolved and the sum is returned. 在上述代码中,我们计算三个元素的总和,如果元素数组的长度超过3,则promise被拒绝,否则promise被解决并返回总和。
We can consume any promise by attaching then() and catch() methods to the consumer.
我们可以通过向消费者附加then()和catch()方法来消费任何promise。
then() method is used to access the result when the promise is fulfilled.
then()方法用于在promise被履行时访问结果。
catch() method is used to access the result/error when the promise is rejected. In the code below, we are consuming the promise:
sumOfThreeElements(4, 5, 6) .then(result=> console.log(result)) .then(result=> console.log(result)) .catch(error=> console.log(error)); .catch(error=> console.log(error)); // In the code above, the promise is fulfilled so the then() method gets executed // 在上述代码中,promise被履行,因此then()方法被执行
sumOfThreeElements(7, 0, 33, 41)
sumOfThreeElements(7, 0, 33, 41) .then(result => console.log(result)) .then(result => console.log(result)) .catch(error=> console.log(error)); .catch(error=> console.log(error)); // In the code above, the promise is rejected hence the catch() method gets executed // 在上述代码中,promise被拒绝,因此catch()方法被执行
Introduced in the ES6 version, classes are nothing but syntactic sugars for constructor functions. They provide a new way of declaring constructor functions in javascript. Below are the examples of how classes are declared and used:
let student2 = new Student("Garry", 673, "7th", "C");
let student2 = new Student("Garry", 673, "7th", "C"); student2.getDetails(); student2.getDetails(); // Returns Name: Garry, Roll no:673, Grade: 7th, Section:C // 返回 姓名:Garry,学号:673,年级:7th,班级:C Key points to remember about classes: - Unlike functions, classes are not hoisted. A class cannot be used before it is declared. 关于类需要记住的关键点:- 与函数不同,类不会进行提升。在声明类之前不能使用它。
A class can inherit properties and methods from other classes by using the extend keyword.
All the syntaxes inside the class must follow the strict mode(‘use strict’) of javascript. An error will be thrown if the strict mode rules are not followed.
Introduced in the ES6 version, generator functions are a special class of functions. They can be stopped midway and then continue from where they had stopped. Generator functions are declared with the function* keyword instead of the normal function keyword:
function* genFunc(){ // Perform operation // 执行操作 } In normal functions, we use the return keyword to return a value and as soon as the return statement gets executed, the function execution stops: 在普通函数中,我们使用return关键字返回一个值,并且一旦return语句被执行,函数执行就会停止:
function normalFunc(){
function normalFunc(){ return 22; return 22; console.log(2); // This line of code does not get executed console.log(2); // 这行代码不会被执行 } In the case of generator functions, when called, they do not execute the code, instead, they return a generator object . This generator object handles the execution. 对于生成器函数,当被调用时,它们不会执行代码,而是返回一个生成器对象。这个生成器对象负责执行。
function* genFunc(){
function* genFunc(){ yield 3; yield 3; yield 4; yield 4; } genFunc(); // Returns Object [Generator] {} genFunc(); // 返回对象 [Generator] {} The generator object consists of a method called next() , this method when called, executes the code until the nearest yield statement, and returns the yield value. For example, if we run the next() method on the above code: 生成器对象包含一个名为 next() 的方法,该方法被调用时,会执行代码直到最近的 yield 语句,并返回 yield 的值。例如,如果我们对上述代码运行 next() 方法:
genFunc().next(); // 返回 {value: 3, done:false} As one can see the next method returns an object consisting of a value and done properties. Value property represents the yielded value. Done property tells us whether the function code is finished or not. (Returns true if finished). 可以看到,next 方法返回一个包含 value 和 done 属性的对象。value 属性表示 yield 的值。done 属性告诉我们函数代码是否执行完毕。(如果执行完毕则返回 true)。
Generator functions are used to return iterators. Let’s see an example where an iterator is returned:
生成器函数用于返回迭代器。让我们看一个返回迭代器的示例:
function* iteratorFunc() {
function* iteratorFunc() { let count = 0; let count = 0; for (let i = 0; i < 2; i++) { for (let i = 0; i < 2; i++) { count++; count++; yield i; yield i; } return count; return count; }
let iterator = iteratorFunc();
let iterator = iteratorFunc(); console.log(iterator.next()); // {value:0,done:false} console.log(iterator.next()); // {value:0,done:false} console.log(iterator.next()); // {value:1,done:false} console.log(iterator.next()); // {value:1,done:false} console.log(iterator.next()); // {value:2,done:true} console.log(iterator.next()); // {value:2,done:true} As you can see in the code above, the last line returns done:true , since the code reaches the return statement. 正如你在上面的代码中所看到的,最后一行返回了 done:true,因为代码执行到了 return 语句。
In javascript, a Set is a collection of unique and ordered elements. Just like Set, WeakSet is also a collection of unique and ordered elements with some key differences: - Weakset contains only objects and no other type.
在 JavaScript 中,Set 是唯一且有序元素的集合。和 Set 一样,WeakSet 也是唯一且有序元素的集合,但有一些关键区别:- WeakSet 只包含对象,不包含其他类型。
An object inside the weakset is referenced weakly. This means, that if the object inside the weakset does not have a reference, it will be garbage collected.
Unlike Set, WeakSet only has three methods, add() , delete() and has() . const newSet = new Set([4, 5, 6, 7]);
const newSet = new Set([4, 5, 6, 7]); console.log(newSet);// Outputs Set {4,5,6,7} console.log(newSet);// 输出 Set {4,5,6,7}
const newSet2 = new WeakSet([3, 4, 5]); //Throws an error
const newSet2 = new WeakSet([3, 4, 5]); // 抛出一个错误
let obj1 = {message:"Hello world"};
let obj1 = {message:"Hello world"}; const newSet3 = new WeakSet([obj1]); const newSet3 = new WeakSet([obj1]); console.log(newSet3.has(obj1)); // true console.log(newSet3.has(obj1)); // true
A callback function is a method that is sent as an input to another function (now let us name this other function "thisFunction"), and it is performed inside the thisFunction after the function has completed execution.
JavaScript is a scripting language that is based on events. Instead of waiting for a reply before continuing, JavaScript will continue to run while monitoring for additional events. Callbacks are a technique of ensuring that a particular code does not run until another code has completed its execution.
In javascript, Map is used to store key-value pairs. The key-value pairs can be of both primitive and non-primitive types. WeakMap is similar to Map with key differences: - The keys and values in weakmap should always be an object.
console.log(classStrength); // 输出 78 console.log(classBenches); // Outputs 39 console.log(classBenches); // 输出 39 console.log(classBlackBoard); // Outputs 1 console.log(classBlackBoard); // 输出 1 As one can see, using object destructuring we have extracted all the elements inside an object in one line of code. If we want our new variable to have the same name as the property of an object we can remove the colon: 可以看出,使用对象解构,我们在一行代码中提取了对象内的所有元素。如果我们希望新变量与对象的属性同名,可以去掉冒号:
const {strength:strength} = classDetails;
const {strength:strength} = classDetails; // The above line of code can be written as: // 上面这行代码可以写成: const {strength} = classDetails; const {strength} = classDetails;
Array destructuring: Before ES6 version:
const arr = [1, 2, 3, 4];
const arr = [1, 2, 3, 4]; const first = arr[0]; const first = arr[0]; const second = arr[1]; const second = arr[1]; const third = arr[2]; const third = arr[2]; const fourth = arr[3]; const fourth = arr[3]; The same example using object destructuring: 使用对象解构的相同示例:
Programers build objects, which are representations of real-time entities, in traditional OO programming. Classes and objects are the two sorts of abstractions. A class is a generalization of an object, whereas an object is an abstraction of an actual thing. A Vehicle, for example, is a specialization of a Car. As a result, automobiles (class) are descended from vehicles (object).
Classical inheritance differs from prototypal inheritance in that classical inheritance is confined to classes that inherit from those remaining classes, but prototypal inheritance allows any object to be cloned via an object linking method. Despite going into too many specifics, a prototype essentially serves as a template for those other objects, whether they extend the parent object or not.
JavaScript design patterns are repeatable approaches for errors that arise sometimes when building JavaScript browser applications. They truly assist us in making our code more stable.
Creational Design Pattern 2. Structural Design Pattern 3. Behavioral Design Pattern. - Creational Design Pattern: The object generation mechanism is addressed by the JavaScript Creational Design Pattern. They aim to make items that are appropriate for a certain scenario.
Structural Design Pattern: The JavaScript Structural Design Pattern explains how the classes and objects we've generated so far can be combined to construct bigger frameworks. This pattern makes it easier to create relationships between items by defining a straightforward way to do so.
Behavioral Design Pattern: This design pattern highlights typical patterns of communication between objects in JavaScript. As a result, the communication may be carried out with greater freedom.
1461. Is JavaScript a pass-by-reference or pass-by-value language?
The variable's data is always a reference for objects, hence it's always pass by value. As a result, if you supply an object and alter its members inside the method, the changes continue outside of it. It appears to be pass by reference in this case. However, if you modify the values of the object variable, the change will not last, demonstrating that it is indeed passed by value.
Generator functions are run by their generator yield by yield which means one output at a time, whereas Async-await functions are executed sequentially one after another.
Async/await provides a certain use case for Generators easier to execute.
The output result of the Generator function is always value: X, done: Boolean, but the return value of the Async function is always an assurance or throws an error.
1463. What are the primitive data types in JavaScript?
A primitive is a data type that isn't composed of other data types. It's only capable of displaying one value at a time. By definition, every primitive is a built-in data type (the compiler must be knowledgeable of them) nevertheless, not all built-in datasets are primitives. In JavaScript, there are 5 different forms of basic data. The following values are available:
The processing of HTML code while the page loads are disabled by nature till the script hasn't halted. Your page will be affected if your network is a bit slow, or if the script is very hefty. When you use Deferred, the script waits for the HTML parser to finish before executing it. This reduces the time it takes for web pages to load, allowing them to appear more quickly.
页面加载时 HTML 代码的处理本质上被禁用,直到脚本停止。如果你的网络有点慢,或者脚本非常庞大,你的页面将受到影响。当你使用 Deferred 时,脚本会等待 HTML 解析器完成后再执行。这减少了网页加载所需的时间,让它们更快地显示出来。
1465. What has to be done in order to put Lexical Scoping into practice?
To support lexical scoping, a JavaScript function object's internal state must include not just the function's code but also a reference to the current scope chain.
var scope = "global scope"; function check() function check() { var scope = "local scope"; var scope = "local scope"; function f() function f() { return scope; return scope; } return f; return f; } Every executing function, code block, and script as a whole in JavaScript has a related object known as the Lexical Environment. The preceding code line returns the value in scope. JavaScript 中每个正在执行的函数、代码块以及整个脚本都有一个相关的对象,称为词法环境。前面的代码行返回作用域中的值。
1467. Explain microtasks vs macrotasks with a real example
JavaScript runs tasks using an event loop. Macrotasks include setTimeout and DOM events. Microtasks include Promises and queueMicrotask. Microtasks always run before the next macrotask. That’s why Promise callbacks execute earlier than setTimeout, even with zero delay.
JavaScript engines use JIT compilation to turn hot code into faster machine code. They create hidden classes to understand object shapes. Inline caching helps reuse property lookups. These optimizations make repeated code much faster. When code behavior changes, the engine may re-optimize.
Memory leaks happen when objects are kept in memory longer than needed. Common causes are global variables, forgotten timers, and event listeners not removed. Detached DOM nodes can also leak memory. You can detect leaks using browser DevTools memory snapshots. Growing memory over time is a red flag.
当对象在内存中保留的时间超过需要时,就会发生内存泄漏。常见原因包括全局变量、被遗忘的定时器以及未移除的事件监听器。分离的 DOM 节点也可能导致内存泄漏。你可以使用浏览器 DevTools 的内存快照来检测泄漏。内存随时间不断增长是一个危险信号。
1470. What is garbage collection in V8 (mark-and-sweep)?
V8 uses garbage collection to free unused memory. It marks all reachable objects starting from roots like globals. Objects not marked are considered unused. These objects are then removed from memory. This process runs automatically in the background.
Deoptimization happens when optimized code becomes invalid. This usually occurs when variable types change unexpectedly. Adding properties to objects dynamically can trigger it. Using mixed types in arrays also causes deopts. Writing consistent code helps avoid this.
TypedArrays store binary data in a fixed format. They are faster and more memory-efficient than normal arrays. They are used in cases like graphics, audio, or handling raw data. Values must match the defined type. This gives better performance.
Structured clones can copy complex objects like Maps and Sets. JSON serialization only works with basic data types. Structured clones also handle circular references. It is used internally by APIs like postMessage. JSON is more limited but widely supported.
结构化克隆可以复制复杂对象,如 Map 和 Set。JSON 序列化仅适用于基本数据类型。结构化克隆还能处理循环引用。它被 postMessage 等 API 在内部使用。JSON 更有限,但广泛受支持。
1474. What is event delegation and why does it matter?
Event delegation means attaching one event listener to a parent instead of many children. Events bubble up to the parent element. This reduces memory usage and improves performance. It also works well for dynamic elements. This is common in large lists.
Expensive reflows and repaints are reduced by batching DOM updates instead of applying changes one by one. Layout reads and writes are kept separate to avoid forced reflows. Repeated style changes inside loops are avoided because they trigger unnecessary recalculations. For animations, CSS transforms and opacity are preferred since they do not affect layout. These practices help keep rendering fast and smooth.
通过批量更新 DOM 而不是逐一应用更改,可以减少昂贵的重排和重绘。布局读取和写入保持分离,以避免强制重排。循环中重复的样式更改会被避免,因为它们会触发不必要的重新计算。对于动画,优先使用 CSS 转换和不透明度,因为它们不影响布局。这些做法有助于保持渲染快速流畅。
1476. How would you design a concurrency limiter for async tasks?
A concurrency limiter controls how many promises run at the same time. Only a fixed number of async tasks are allowed to execute, while extra tasks wait in a queue. When one task finishes, the next task from the queue is started. This approach prevents API overload and browser performance issues. A simple queue-based design keeps execution predictable and stable.
并发限制器控制同时运行多少个 Promise。只允许固定数量的异步任务执行,而额外的任务在队列中等待。当一个任务完成时,队列中的下一个任务开始执行。这种方法防止了 API 过载和浏览器性能问题。简单的基于队列的设计可保持执行可预测且稳定。
JavaScript Tricky Questions
1477. What is the difference between null and undefined? When do you get each one?
undefined means a variable exists but has no value assigned yet. null means the value is intentionally set to nothing. JavaScript usually gives undefined automatically. Developers usually assign null themselves. Both represent “no value” but are used differently.
Truthy values act like true in conditions. Falsy values act like false. JavaScript has only a few falsy values. "0" is truthy because it is a non-empty string. Only empty strings are falsy.
Hoisting means JavaScript moves declarations to the top before execution. var declarations are hoisted but initialized as undefined. let and const are hoisted but not accessible early. Function declarations are fully hoisted. Function expressions are not.
TDZ is the time between entering a scope and declaring a let or const variable. Accessing the variable in this zone throws an error. This prevents using variables before they are properly declared. It helps catch bugs early. var does not have TDZ.
var is function-scoped and can be redeclared and reassigned. let is block-scoped and can be reassigned but not redeclared in the same scope. const is also block-scoped but cannot be reassigned. var is hoisted in a confusing way. In modern JavaScript, let and const are preferred.
A closure is when a function remembers variables from its outer scope. Even after the outer function finishes, the inner function can still access them. This is useful for keeping data private. Closures are common in counters and helper functions. They help control access to variables.
this refers to the object that is calling the function. In a normal function, this depends on how the function is called. In arrow functions, this is taken from the surrounding scope. Arrow functions do not have their own this. This avoids many common bugs.
map() creates and returns a new array. forEach() only loops and does not return anything. map() is used when you want transformed data. forEach() is used for side effects like logging. map() is more functional and cleaner.
slice() returns a new array and does not change the original one. splice() modifies the original array. slice() is used to copy part of an array. splice() is used to add or remove elements. This difference is very important in interviews.
push adds elements to the end of the array. pop removes elements from the end. unshift adds elements to the beginning. shift removes elements from the beginning. shift and unshift are slower because they reindex the array.
Event bubbling means the event starts at the element where it happens and then moves upward to parent elements. Event capturing works in the opposite direction, starting from the parent and moving down to the target. Event delegation uses bubbling by placing a single event listener on a parent element. This listener handles events for all child elements. It is very useful for large lists and dynamically added elements.
Synchronous code runs step by step and blocks execution until each step finishes. Asynchronous code allows other tasks to run while waiting for long operations to complete. This makes applications faster and more responsive. In browsers, async tasks include API calls and timers. In Node.js, file system and database operations are asynchronous.
同步代码逐步运行,并在每一步完成前阻塞执行。异步代码在等待长时间操作完成时允许其他任务运行。这使得应用更快速、更响应。在浏览器中,异步任务包括 API 调用和定时器。在 Node.js 中,文件系统和数据库操作是异步的。
Promise.all() waits for all promises but fails immediately if even one promise rejects. This is useful when all results are required for the next step. Promise.allSettled() waits for every promise to finish, whether it succeeds or fails. It returns the status of each promise. This is useful when partial results are acceptable.
No. If we can accomplish our goals using simple JavaScript, then we should avoid using jQuery. It is because the jQuery library is always xx kilobytes in size, thus there is no use in wasting bandwidth. And because jQuery is built on top of javascript, it has numerous functions that are more complicated than the simple job you can accomplish with javascript. jQuery will also load all dependencies. It will have some speed issues as compared to the javascript code.
Yes, that is possible. With the release of jQuery 1.6, a new method called "jQuery.holdReady(hold)" was added. This function allows you to postpone the execution of the document.ready() event. The document.ready() event is triggered as soon as your DOM is ready, however, there may be occasions when you wish to load extra JavaScript or plugins that you have referenced.
event.stopPropagation() stops the event from propagating up the DOM tree, preventing any parent handlers from being notified of the event. For example, if a link with a click method is linked inside of a DIV or FORM that also has a click method attached, the DIV or FORM click method will not fire.
event.stopPropagation() 会阻止事件在 DOM 树中向上传播,从而防止任何父级处理器收到该事件的通知。例如,如果一个带有点击方法的链接位于一个也附加了点击方法的 DIV 或 FORM 内部,那么 DIV 或 FORM 的点击方法将不会触发。
1493. What Are the Benefits of Using Jquery Instead of Javascript in an Asp.net Web Application?
在 Asp.net Web 应用程序中,使用 jQuery 而不是 JavaScript 有哪些好处?
Below are some of the benefits of using jQuery instead of javascript in ASP.net Web Application - - Jquery is well-written optimized javascript code, thus it will execute quicker until we create the same standard optimized javascript code.
以下是在 ASP.net Web 应用程序中使用 jQuery 而不是 JavaScript 的一些好处:- jQuery 是编写良好的优化 JavaScript 代码,因此它会执行得更快,除非我们创建同样标准的优化 JavaScript 代码。
Jquery is javascript code that is succinct, which implies that it requires the least amount of code to do the same functionality as javascript.
Jquery makes Javascript development faster since much of the functionality is already provided in the library and we only need to access it.
Because Jquery supports cross-browser compatibility, we save time on supporting all browsers.
1494. Explain the use of event.preventDefault() method.
Event.PreventDefault is a jQuery event that stops an event from firing when the user clicks on a link or other trigger. It basically stops the default behaviour of the triggers and allows any other event to occur. It is useful for preventing unwanted events from firing when a user clicks on a link or other trigger. This can be useful when you want to prevent users from accidentally clicking on links that open up new windows or tabs.
When you use an event like click or keypress, you can prevent the event from firing by adding the event.preventDefault() method to the event object. When you use event.preventDefault() , the event will not fire unless the user clicks on a link or other trigger.
Example - Assume you're developing an AJAX-based application in which you need to submit form data through AJAX when a button in the form is clicked. So, if you click on a button without preventing it, the button behaves normally and the website reloads. As a result, the other event will not occur when you click the button. So, if we use prevent default there, we can skip the button's default behaviour and instead perform the AJAX event and alter the HTML DOM accordingly.
There are two methods for obtaining a query string using regular expressions. - String-based approach: This method aids in the generation of Strings by comparing similar regular expressions using the.replace() function.
Regular Express Based Approach: When compared to strings in JavaScript, the regular expression technique is the most powerful method for extracting a query string and pattern. Using the.exec() and.test() methods to compare against patterns. Other String methods include match(), matchAll(), replace(), search(), and split().
1496. In jQuery, what is the difference between $(this) and this.
$(this) is a jQuery object, whereas this is a JavaScript global object reference. We may refer to DOM elements in HTML documents using this.
$(this) refers to the parent object, whereas this is a DOM element that, in the case of an array, represents an object with the .each() method, which shows the current iteration.
We use this as an alternative to this.parent() to refer to the parent object in JavaScript. This is more convenient than using this.parent(). We can also use this to refer to other elements in HTML, as in an ul element:
我们将其用作 this.parent() 的替代方案,用于在 JavaScript 中引用父对象。这比使用 this.parent() 更方便。我们也可以使用 this 来引用 HTML 中的其他元素,例如在 ul 元素中: var myElement = $('ul').each(function() { var myElement = $('ul').each(function() { var childElement = this.parent().nextSibling(); var childElement = this.parent().nextSibling(); }); This is useful when you need to iterate over a list of elements and their children, but you do not want to reference the parent object. 当您需要遍历一组元素及其子元素,但不想引用父对象时,这非常有用。
1497. Explain the benefits of using a CDN for the jQuery files.
Hosting jQuery on a Content Delivery Network (CDN) improves availability and performance at a reduced cost and with less network traffic, improves latency (the time it takes to send and receive a data packet from the server), and provides a device-specific version of the contents.
CDNs are a great way to host your JavaScript and CSS files. By caching these files, you can reduce the amount of time it takes for your site to load, making it faster and more responsive. This is especially important for sites that serve large amounts of content, such as blogs or e-commerce sites. By using a CDN, you can also reduce the number of load times that occur when visitors access your site. In addition, by hosting your JavaScript and CSS files on a CDN, you can also reduce the amount of bandwidth that is consumed by your site.
Example - It makes it simple to maintain responsiveness for mobile screen sizes, as well as safe storage space for important data or files.
示例 - 它使维护移动屏幕尺寸的响应性变得简单,同时为重要数据或文件节省存储空间。
Caching JavaScript and CSS files on a CDN is an important optimization that should be considered when building a site with a lot of JavaScript and CSS files.
The functionality of jquery.min.js and jquery.js is the same. However, If you are serving a page that contains a lot of JavaScript, it is a good idea to minify it. Minifying JavaScript (jquery.min.js) reduces the size of your file and makes it faster to load on all platforms. Minifying your code also reduces the chances that erroneous code will be rendered as a malicious attack because it makes it more difficult to test. With minified JavaScript, you will get better page performance, faster loading, and shorter wait times for your visitors.
There are also some of the major advantages of the jquery.min.js. - - When JS files are minified in a production environment, they load faster and provide faster and better page performance.
Minifying a script also reduces the size of the file in the server’s temporary directory and browser cache, which results in a faster download and a smaller server response.
Another advantage of using minified JS is that it removes the need to include any external JS files in the HTML document. This makes it easier to structure the code and easier to edit the code.
1499. Explain the operation of the jQuery connect() method.
The connect() method of jQuery is a utility function that allows you to create a new jQuery object and pass it to the jQuery object's constructor. This allows you to create a new object with the same functionality as the original object, but without having to manually set up the object's properties. For example, you can pass in an existing jQuery object and it will be automatically set up to use the same properties as the original object.
When using connect() method, you can pass in a callback function that will be called when the new object is ready. The callback function can be used to perform any additional setup that needs to be done before the new object can be used.
For example - you can set up a data source using the data() method of jQuery. When using connect() method, you can pass in a callback function that will be called when the new object is ready.
jQuery Coding Questions
1500. Can you tell the difference between prop() and attr()s?
Both prop() and attr() can be used to get or set the value of the specified property of an element attribute.
The attr() gives the default value of a property whereas prop() returns its current value.
Conclusion
结论 A JavaScript library called jQuery makes it simple to construct dynamic web pages. It contributes to the efficiency and interactivity of web applications. It also facilitates the usage of a number of functions that may be used to alter data, which speeds up the development process. JQuery has some important uses like - DOM manipulations, Availability of different plugins according to the work, Animation and AJAX Support, Support for Cross browsers, etc. jQuery is a lightweight library that can be easily integrated into any website. We have seen all the most frequently asked questions related to jquery in the interview. 一个名为 jQuery 的 JavaScript 库使构建动态网页变得简单。它有助于提高 Web 应用的效率和交互性。它还促进了多种可用于修改数据的函数的使用,从而加快了开发过程。jQuery 有一些重要的用途,如 - DOM 操作、根据工作提供不同的插件、动画和 AJAX 支持、跨浏览器支持等。jQuery 是一个轻量级库,可以轻松集成到任何网站中。我们已经介绍了面试中所有最常问的与 jQuery 相关的问题。
function getMinsSeconds() { var dt = new Date(); var dt = new Date(); return dt.getMinutes()+":"+dt.getSeconds(); return dt.getMinutes()+":"+dt.getSeconds(); }
For the above code, the difference between the start and end times will be 10 seconds.
This is because .promise() will wait for all animations (here, all fadeOut() calls) to complete, the last one will complete 10 seconds (i.e. 5 * 2 = 10 seconds) after the fadeOut() starts.
1503. Write A Jquery Code Snippet To Sort A String Array?
$(document).ready(function(){ var arr = [ "jQuery","Interview","Questions","By","InterviewBit"]; var arr = [ "jQuery","Interview","Questions","By","InterviewBit"]; sortedArr = arr.sort(); sortedArr = arr.sort(); $("#elementId").html(sortedArr.join("")); $("#elementId").html(sortedArr.join("")); }); The Output will be 输出结果将是
The .promise() method returns a dynamically generated promise that is resolved when all actions of a certain type bound to the collection, queued or not, have ended.
The method takes two optional arguments:
type - The default type is “fx” which indicates that the returned promise is resolved only when all animations of the selected elements have been completed.
type - 默认类型为“fx”,表示返回的承诺仅在所选元素的所有动画完成后才被解析。 target - If a target object is specified, .promise() will attach to promise to that specified object and then return it rather than creating a new one. target - 如果指定了目标对象,.promise() 会将承诺附加到该指定对象上,然后返回它,而不是创建一个新的承诺。
1505. Can you write a jQuery code selector that needs to be used for querying all elements whose ID ends with string “IB”?
The code document.getElementById( "interviewBit" ); is more efficient because its the pure JavaScript version.
The reason being jQuery is built on top of JavaScript and internally uses its methods to make DOM manipulation easier. This introduces some performance overhead. We need to remember that jQuery is not always better than pure JavaScript and we need to use it only if it adds advantage to our project.
1508. Write a code snippet for preventing the default behavior of the submit button for performing another event.
jQuery.ajax() allows the creation of highly-customized AJAX requests, with options for how long to wait for a response, what to do once the request is successful, how to handle a failure scenarios, whether the request to be sent is blocking (synchronous) or non-blocking (asynchronous), what format to expect as the response, and many more customizable options.
jQuery.get() is uses jQuery.ajax() underneath to create an AJAX request typically meant for simple retrieval of information.There are various other pre-built AJAX requests given by jQuery such as:
jQuery.post() for performing post requests
jQuery.post()用于执行POST请求 jQuery.getScript() meant for loading and then executing a JavaScript file from the server using GET request. jQuery.getScript()旨在通过GET请求从服务器加载并执行一个JavaScript文件。
jQuery.getJSON() for loading JSON-encoded data from the server using a GET HTTP request.
The given code first selects all the elements and applies width of 500px to them and adds all the elements to the elements selection after which the code can finally change the background color to yellow for all the and elements
The given code is an example of method chaining in jQuery which is used to accomplish a couple of things in one single instruction.
1511. Consider the following code that exists in following HTML with the CSS:
Write jQuery code to animate the #expand div, expanding it from 50 50 pixels to 300 300 pixels within five seconds. 编写jQuery代码来给#expand div添加动画效果,使其在五秒内从50×50像素扩展到300×300像素。 We can do this by using the animate() function. We first need to have access to the div element which has id value of expand and then apply animate function on the element as follows: 我们可以通过使用animate()函数来实现这一点。首先需要访问id值为expand的div元素,然后在该元素上应用animate函数,如下所示:
jQuery provides the ajax() method to perform an AJAX (asynchronous HTTP) request.
Syntax: $.ajax({name:value, name:value, ... }). The parameters specify one or more values of name-value pairs.
url: this name specifies the URL to send the request to. Default is the current page.
url: 此名称指定发送请求的 URL。默认为当前页面。 success(result,status,xhr): success callback function which runs when the request succeeds success(result,status,xhr): 成功回调函数,在请求成功时运行
error(xhr,status,error): A function to run if the request fails.
error(xhr,status,error): 在请求失败时运行的函数。
async: Boolean value that indicates whether the request should be handled asynchronous or not. The default value is true.
async: 布尔值,指示请求是否应异步处理。默认值为 true。
complete(xhr,status): A function to run when the request is completed (after success and error functions are handled)
complete(xhr,status): 在请求完成时运行的函数(在成功和错误函数处理之后)
xhr: A function used for creating the XMLHttpRequest object - Example:
Following are some of the disadvantages of Kotlin:
以下是 Kotlin 的一些缺点:
In Kotlin, there are a few keywords that have non-obvious meanings: internal, crossinline, expect, reified, sealed, inner, open. Java has none of these.
Checked exceptions are likewise absent in Kotlin. Although checked exceptions have become less prominent, many programmers believe them to be an effective technique to ensure that their code is stable.
A lot of what happens in Kotlin is hidden. You can almost always trace the logic of a program in Java. When it comes to bug hunting, this can be really useful. If you define a data class in Kotlin, getters, setters, equality testing, tostring, and hashcode are automatically added for you.
Learning resources are limited. The number of developers who are moving to Kotlin is growing, yet there is a small developer community accessible to help them understand the language or address problems during development.
Kotlin has variable compilation speed. In some situations, Kotlin outperforms Java, particularly when executing incremental builds. However, we must remember that when it comes to clean builds, Java is the clear winner.
1514. Differentiate between launch / join and async / await in Kotlin.
The launch command is used to start and stop a coroutine. It's as though a new thread has been started. If the code inside the launch throws an exception, it's considered as an uncaught exception in a thread, which is typically written to stderr in backend JVM programs and crashes Android applications. Join is used to wait for the launched coroutine to complete before propagating its exception. A crashed child coroutine, on the other hand, cancels its parent with the matching exception.
The async keyword is used to initiate a coroutine that computes a result. You must use await on the result, which is represented by an instance of Deferred. Uncaught exceptions in async code are held in the resultant Deferred and are not transmitted anywhere else. They are not executed until processed.
A backing field is an auto-generated field for any property that may only be used inside accessors (getter or setter) and will only be present if it utilizes the default implementation of at least one of the accessors, or if a custom accessor refers to it through the field identifier. This backing field is used to avoid an accessor's recursive call, which would result in a StackOverflowError.
Fields are not allowed in Kotlin classes. When employing custom accessors, however, it is occasionally required to have a backing field. Kotlin includes an automatic backing field for these purposes, which may be accessed by the field identifier.
var marks: Int = someValue get() = field get() = field set(value) { set(value) { field = value field = value } Explanation:- Here the field identifier acts as a reference to the property “marks” value in the get() and set() method. So, whenever we call the get(), we get the field’s value returned. Similarly, whenever we call the set(), we set the “marks” property value to “value”. 解释:- 这里,字段标识符在 get() 和 set() 方法中充当对属性“marks”值的引用。因此,每当我们调用 get() 时,就会返回字段的值。类似地,每当我们调用 set() 时,就将“marks”属性的值设置为“value”。
1516. What do you understand about sealed classes in Kotlin?
Kotlin introduces a crucial new form of class that isn't seen in Java. These are referred to as "sealed classes." Sealed classes, as the name implies, adhere to constrained or bounded class hierarchies. A sealed class is one that has a set of subclasses. When it is known ahead of time that a type will conform to one of the subclass types, it is employed. Type safety (that is, the compiler will validate types during compilation and throw an exception if a wrong type has been assigned to a variable) is ensured through sealed classes, which limit the types that can be matched at compile time rather than runtime.
sealed class className Another distinguishing aspect of sealed classes is that their constructors are by default private. Due to the fact that a sealed class is automatically abstract, it cannot be instantiated. 密封类的另一个显著方面是,它们的构造函数默认是私有的。由于密封类自动是抽象的,因此它不能被实例化。
For example,
例如,
// KOTLIN
// KOTLIN sealed class Sample { sealed class Sample { class A : Sample() { class A : Sample() { fun print() fun print() { println("This is the subclass A of sealed class Sample") println("这是密封类Sample的子类A") } } class B : Sample() { class B : Sample() { fun print() fun print() { println("This is the subclass B of sealed class Sample") println("这是密封类Sample的子类B") } } } fun main() fun main() { val obj1 = Sample.B() val obj1 = Sample.B() obj1.print() obj1.print()
val obj2 = Sample.A()
val obj2 = Sample.A() obj2.print() obj2.print() } Output:- 输出:-
This is the subclass B of sealed class Sample
这是密封类Sample的子类B This is the subclass A of sealed class Sample 这是密封类Sample的子类A Explanation:- In the above code, we have created a sealed class named “Sample” and we have created two sub classes within it named “A” and “B”. In the main function, we create an instance of both the sub classes and call their “print” method. 解释:- 在上面的代码中,我们创建了一个名为“Sample”的密封类,并在其中创建了两个名为“A”和“B”的子类。在主函数中,我们创建了两个子类的实例,并调用了它们的“print”方法。
1517. Explain suspend function in the context of Kotlin.
A function that may be started, halted, then resumed is known as a suspend function. One of the most important things to remember about the suspend functions is that they can only be invoked from another suspend function or from a coroutine. Suspending functions are merely standard Kotlin functions with the suspend modifier added, indicating that they can suspend coroutine execution without blocking the current thread. This means that the code you're looking at may pause execution when it calls a suspending function and restart execution at a later time. However, it makes no mention of what will happen to the present thread in the meantime.
Suspending functions can call any other ordinary functions, but another suspending function is required to suspend the execution. Because a suspending function cannot be called from a regular function, numerous coroutine builders are supplied, allowing you to call a suspending function from a non-suspending scope like launch, async, or runBlocking.
The Kotlin standard library includes numerous functions that aid in the execution of a block of code within the context of an object. When you use a lambda expression to call these functions on an object, temporary scope is created. These functions are referred to as Scope functions. The object of these functions can be accessed without knowing its name. Scope functions make code more clear, legible, and succinct, which are key qualities of the Kotlin programming language.
Following are the different types of Scope functions available in Kotlin:- - let:- Context object: it Return value: lambda resultThe let function is frequently used for null safety calls. For null safety, use the safe call operator(?.) with ‘let'. It only runs the block with a non-null value.
apply:-Context object: thisReturn value: context object“Apply these to the object,” as the name suggests. It can be used to operate on receiver object members, primarily to initialise them.
with:-Context object: thisReturn value: lambda resultWhen calling functions on context objects without supplying the lambda result, ‘with' is recommended.
run:-Context object: this Return value: lambda resultThe ‘run' function is a combination of the ‘let' and ‘with' functions. When the object lambda involves both initialization and computation of the return value, this is the method to use. We can use run to make null safety calls as well as other calculations.
also:-Context object: itReturn value: context objectIt's used when we need to do additional operations after the object members have been initialised.
1519. What do you understand about coroutines in the context of Kotlin?
Unlike many other languages with equivalent capabilities, async and await are neither keywords nor part of Kotlin's standard library. JetBrains' kotlinx.coroutines library is a comprehensive library for coroutines. It includes a number of high-level coroutine-enabled primitives, such as launch and async. Kotlin Coroutines provide an API for writing asynchronous code in a sequential manner.
Coroutines are similar to thin threads. Coroutines are lightweight since they don't allocate new threads when they're created. Instead, they employ pre-defined thread pools as well as intelligent scheduling. The process of deciding which piece of work you will do next is known as scheduling. Coroutines can also be paused and resumed in the middle of their execution. This means you can have a long-term project that you can work on incrementally. You can pause it as many times as you want and continue it whenever you're ready.
1520. Differentiate between lateinit and lazy initialisation. Explain the cases when you should use lateinit and when you should use lazy initialisation.
Following are the differences between lateinit and lazy initialisation:-
以下是 lateinit 和 lazy 初始化之间的区别:-
lateinit
lazy initialisation lazy 初始化
The main purpose is to delay the initialisation to a later point in time. 主要目的是将初始化延迟到稍后的时间点。
The main purpose is to initialise an object only when it is used at a later point in time. Also, a single copy of the object is maintained throughout the program. 主要目的是仅在稍后使用时才初始化对象。此外,在整个程序中保持对象的单个副本。
It's possible to initialise the object from anywhere in the program. 可以从程序中的任何位置初始化对象。
Only the initializer lambda can be used to initialise it. 只能使用初始化 lambda 来初始化它。
Multiple initializations are possible in this case. 在这种情况下可以多次初始化。
Only a single initialisation is possible in this case. 在这种情况下只能进行一次初始化。
It's not thread-safe. In a multi-threaded system, it is up to the user to correctly initialise. 它不是线程安全的。在多线程系统中,由用户来正确初始化。
Thread-safety is enabled by default, ensuring that the initializer is only called once. 默认启用线程安全,确保初始化器只被调用一次。
It works only with var. 它仅适用于 var。
It works only with val. 它仅适用于 val。
The isInitialized method is added to verify if the value has previously been initialised. 添加 isInitialized 方法来验证值是否已被初始化。
It is impossible to uninitialize a property. 无法取消初始化属性。
Properties of primitive types are not allowed 不允许使用原始类型的属性
Allowable on primitive type properties. 允许用于原始类型的属性。
There are a few easy principles to follow when deciding whether to use lateinit or lazy initialisation for property initialization: - Use lateInit if properties are mutable (i.e., they may change later).
Use lateinit if properties are set externally (for example, if you need to pass in an external variable to set it). There is still a way to use lazy, but it isn't as obvious.
If they're only meant to be initialised once and shared by everybody, and they're more internally set (depending on a class variable), then lazy is the way to go. We could still use lateinit in a tactical sense, but utilising lazy initialisation would better encapsulate our initialization code.
1521. Explain lazy initialization in the context of Kotlin.
There are some classes whose object initialization is so time-consuming that it causes the entire class creation process to be delayed. Lazy initialisation helps in such problems. When we declare an object using lazy initialisation, the object is initialised only once when the object is used. If the object is not used throughout, the object is not initialised. This makes the code more efficient and faster.
// KOTLIN class FastClass { class FastClass { private val slowObject: SlowClass = SlowClass() private val slowObject: SlowClass = SlowClass() } We are generating a large object here, which will cause the development of the FastClass to be slow or delayed. There may be times where the SlowClass object isn't required. As a result, the lazy keyword can assist you in this situation: 我们在这里生成了一个大型对象,这将导致 FastClass 的构建变得缓慢或延迟。有时可能不需要 SlowClass 对象。因此,lazy 关键字可以帮助你解决这种情况:
class FastClass {
class FastClass { private val slowObject: SlowClass by lazy { private val slowObject: SlowClass by lazy { SlowClass() SlowClass() } } For example, 例如,
// KOTLIN
// KOTLIN class FastClass { class FastClass { private val slowObject: SlowClass by lazy { private val slowObject: SlowClass by lazy { println("Slow Object initialised") println("Slow Object initialised") SlowClass() SlowClass() }
fun access() {
fun access() { println(slowObject) println(slowObject) } } fun main(args: Array) { fun main(args: Array) { val fastClass = FastClass() val fastClass = FastClass() println("FastClass initialised") println("FastClass initialised") fastClass.access() fastClass.access() fastClass.access() fastClass.access() } Output:- 输出:-
FastClass initialised
FastClass initialised Slow Object initialised Slow Object initialised SlowClass@2b12fkk7 SlowClass@2b12fkk7 SlowClass@2b12fkk7 SlowClass@2b12fkk7 Explanation:- In the above code, we have instantiated an object of the SlowClass inside the class structure of the FastClass using lazy initialisation. The object of the SlowClass is generated only when it is accessed in the above code, that is, when we call the access() method of the FastClass object and the same object is present throughout the main() method. 解释:- 在上述代码中,我们使用惰性初始化在FastClass的类结构内部实例化了一个SlowClass对象。SlowClass的对象仅在上述代码中访问它时才生成,即当我们调用FastClass对象的access()方法时,并且同一个对象在整个main()方法中始终存在。
1522. What do you understand about lateinit in Kotlin? When would you consider using it?
lateinit is an abbreviation for late initiation. If you don't want to initialize a variable in the constructor and instead want to do it later, and you can guarantee the initialization before using it, use the lateinit keyword to declare that variable. It won't start allocating memory until it's been initialized. Lateinit cannot be used for primitive type attributes like Int, Long, and so on. Because the lateinit variable will be initialized later, you cannot use val. When a lateinit property is accessed before it has been initialized, a special exception is thrown that explicitly identifies the property and the fact that it hasn't been initialized.
// KOTLIN lateinit var test: String lateinit var test: String fun testFunction() { fun testFunction() { test = "Interview" test = "Interview" println("The length of string is "+test.length) println("The length of string is "+test.length) test = "Bit" test = "Bit" } When the testFunction is called, we get the following output:- 当调用 testFunction 时,我们得到以下输出:-
9 There are a few scenarios in which this is particularly useful, for example: - Variables that are initialized in lifecycle methods in Android;
有几个场景特别有用,例如:- 在 Android 的生命周期方法中初始化的变量;
Using Dagger for DI: injected class variables are initialized outside of the constructor and independently;
Setup for unit tests: in a @Before - annotated function, test environment variables are initialized;
Annotations in Spring Boot (for example, @Autowired).
1523. Which one is better to use - val mutableList or var immutableList in the context of Kotlin?
在 Kotlin 上下文中,val mutableList 和 var immutableList 哪个更好用?
The program's design clarity is improved by using mutable and immutable lists. This is done to have the developer think about and clarify the collection's purpose.
使用可变和不可变列表可以提高程序的设计清晰度。这样做是为了让开发者思考并明确集合的用途。
We use a mutable list if the collection will alter as part of the design. On the other hand, we use an immutable list if the model is only meant to be viewed.
Val and var serve a distinct purpose than immutable and mutable lists. The val and var keywords specify how a variable's value/reference should be handled. We use var when the value or reference of a variable can be altered at any moment. On the other hand, we use val when a variable's value/reference can only be assigned once and cannot be modified later in the execution.
val 和 var 的用途与不可变列表和可变列表不同。val 和 var 关键字指定如何处理变量的值/引用。当变量的值或引用可以在任何时刻改变时,我们使用 var。另一方面,当变量的值/引用只能赋值一次且不能在后续执行中修改时,我们使用 val。
Immutable lists are frequently preferred for a variety of reasons: - They promote functional programming, in which state is passed on to the next function, which constructs a new state based on it, rather than being altered. This is evident in Kotlin collection methods like map, filter, reduce, and so forth.
It's often easier to understand and debug software that doesn't have any side effects (you can be sure that the value of an object will always be the one at its definition).
Because no write access is required in multi-threaded systems, immutable resources cannot induce race conditions. However, there are some disadvantages of using immutable lists as well. They are as follows : - Copying large collections simply to add/remove a single piece is very expensive.
When you need to alter single fields frequently, immutability can make the code more difficult. Data classes in Kotlin provide a built-in copy() method that allows you to clone an instance while changing only part of the fields' values.
1524. Write down some iPhone and iPad testing tools.
As the name suggests, cloud-based mobile testing involves the use of an online cloud platform rather than an on-premises environment to test mobile applications. This tool makes all devices available on one platform so that testers connected to a cloud can access them. In this way, developers and QA teams can communicate effectively from all over the world. During the testing process, testers have access to a range of devices, operating systems, screen sizes, network carriers, etc.
While doing mobile testing on cloud computing, the tester faces the following challenges: - In spite of Cloud services being advertised as cost-saving solutions, they can actually cost more.
In mobile applications, A/B testing, also known as split testing or bucket testing, is the practice of testing different user experiences. With A/B testing for mobile applications, audiences are split into two (or more) groups and a variable is tested to see how it affects user behavior. By using this, we can identify and deliver the best possible user experience. In iOS app , it is possible to conduct A/B testing in three steps: - Step 1: Configuring a test that prepares two versions of your iOS application (namely A and B) with required test metrics
Step 2: Testing two of the above iOS versions simultaneously
Step 3: Analyzing test results and selecting the best version to release
In the above diagram, audience/visitors are split into two groups to check two versions of the application (Variation A and Variation B). Conversion rate (% of visitors to your application who reach their desired goal out of total visitors) of variation A and B is 23% and 11% respectively. Now, you can identify which version is best and deliver the best possible user experience.
The Android testing framework is an open-source framework and one of the most widely used frameworks for testing Android applications. Developers use the Android testing framework to record user interface tests for unit devices and Android devices. UI (User Interface) testing ensures that your application responds to a user's actions on the device with the correct UI output. There are three segments in the Android testing framework: - Application Package: This package contains the target application to be tested.
Instrumentation Test Runner: As a Test Case Runner, it enables test cases to run/execute on the target application. Essentially, it consists of two parts: an SDK tool for creating tests, and MonkeyRunner, an API tool that allows you to write programs to control Android devices outside of Android code.
Test Package: This package consists of two parts: test case classes (includes test methods to be performed on target application) and mock objects (include mock data used as sample input for test cases). Most popular Android test frameworks - Poppy
最受欢迎的Android测试框架 - Poppy
Detox
Express
Calabash
UI Automator
1530. What are the best practices for Android Testing?
The following are some of the best common practices for Android testing: - When writing the code simultaneously, the developers must also prepare the test cases.
以下是Android测试的一些常见最佳实践:- 在编写代码的同时,开发人员也必须准备测试用例。
Detailed documentation and storage of the test cases are essential to reusability.
Implement continuous integration and run tests as soon as there is a change to the code.
Avoid rooting your smartphone (which gives you privileged control over the operating system and enables you to change system files, software code, etc.) and using emulators to obtain the most accurate results.
1531. What do you mean by Robo-electric testing framework?
Testing an Android application on a device or emulator is not always easy. It usually takes a lot of effort and time to build test cases. To address this challenge, a robotic testing framework is considered. Using the Robolectric framework, Android tests can be run directly on desktop JVMs (Java Virtual Machines), without the need for a device or emulator. Thus, you don't need to set up anything extra to run Android tests within your development environment. It makes Android application testing faster and more reliable.
Rather than using classes in Android, Robotetrics used shadow objects. If Robolectric implements a method, this method call is forwarded to the shadow object and it behaves similarly to the Android implementation. In cases where a shadow object does not implement a method, it returns a default value such as null or 0.
Aside from affordability, it is essential to consider the following factors when choosing a test automation tool: - Platform compatibility: Make sure the tool is compatible with your current and future target platforms
Having secure mobile applications is very important for the business, which in turn, requires testing for the security of all mobile applications. Security testing is therefore considered important testing by testers. Authentication, authorization, data security, hacking vulnerabilities, session management, etc., are all included in mobile application security testing. This test can ensure there aren't any loopholes allowing data to be lost. Testing is meant to identify any potential threats or vulnerabilities that could allow external parties to access private information on the mobile device.
Testing mobile applications for security include the following: - Check if the application supports multiple users without interfering with their data.
测试移动应用的安全性包括以下内容:- 检查应用是否支持多个用户而不干扰他们的数据。
Verifies sensitive data is communicated using a decryption or encryption method.
Verifies that anyone with unauthorized access to files stored in the app is not accessing them.
Identify sensitive areas of the application to ensure it does not receive any malicious content.
Validates an application's resistance to malicious attacks or cyber-attacks and ensures that developers adhere to security practices when programming.
1534. What criteria should be considered when performing a sanity test on the mobile application?
When we don't have enough time for testing and regression is needed, we perform sanity testing. In, sanity testing, the QA engineer confirms that all available menus, functions, and commands are working properly in a product application and project before release. The following criteria should be considered when performing sanity tests on the mobile application: - Remember to take into account the installation and uninstallation processes of the application when conducting this test. Verify that the installation and uninstallation go smoothly.
A Test Case Runner is a software tool that allows mobile applications to be tested. In essence, runners act as an environment that represents both the device and the end-users. A near-exact simulation of the user environment is generated and the application's functionalities are tested just as if a human were using the device. It helps determine whether the application is ready for launch. Commonly called an instrumentation test runner, it runs test cases on an application smoothly.
The mobile usability testing process involves evaluating mobile products according to how they are used by end-users, so the goal is to make them as user-friendly as possible. It can assist you in evaluating the functionality of your mobile app and also ensure that your users have an easy time navigating your app. Mobile usability testing entails doing research and finding problems early on. In order to determine the efficiency of the target audience, it evaluates the application based on the following criteria: - Effectiveness
Satisfaction It is very important to get usability testing in place from the initial stage of application design, and this should not be done only when the application is completed. Usability testing requires excessive involvement of users, and output can affect application design, which is very difficult to change in later stages of the project.
A popular open-source testing tool for mobile applications is Appium, which automates tests for platforms like Android, iOS, and Windows. It is used to automate the testing of native, hybrid, and web applications. This tool is quite popular due to its availability, free nature, low memory consumption and integration with other external applications such as Selenium WebDriver and Selenium Grid. The tool is cross-platform, meaning the same test can be run on multiple platforms. Appium can test multiple devices simultaneously.
Test scenarios are simple sets of functionalities (detailed documents of test cases) that can be automated or manually tested in a mobile application or website. In addition to providing insight into the positive and negative characteristics of an application or website, test scenarios are often very useful to the testing team. Because testers test applications from the user's perspective, they must put themselves in the position of the user during a test scenario.
One of the most challenging aspects of app testing is writing test scenarios for mobile applications. However, scenario-based testing is the best method for testing complicated systems, so be sure to keep these tips in mind when preparing mobile application testing scenarios. - Examine the Requirement Document, including the BRS (Business Requirement Specification), SRS (Software Requirement Specification), as well as the FRS (Functional Requirement Specification) pertaining to the SUT (System Under Test).
Design simple test scenarios rather than complex ones. Keep them concise and simple, so they are easy to understand.
Generate test scenarios that cover all possible features of the target application. Users and business flows involved in the operation of the application/website must be covered by these scenarios.
Put an emphasis on project methodology.
Identify the priorities of your customers and devise test scenarios accordingly.
Keep an eye on the expected outcome.
1540. List out some mobile application testing scenarios.
Mobile Functional Testing means testing the functions of mobile applications, such as user interactions and transactions. Functional testing is performed by mobile application developers to ensure application quality, meet user expectations, and reduce the risk of errors in mobile applications. The most common scenarios in functional testing include: - Verify that all required mandatory fields work as intended.
Every time an application starts/stops, make sure the application works correctly.
If the app is running, check whether SMS can be stored, processed, and received.
Check if the device can perform multitasking functions when necessary while the application is running.
Verify that the application provides access to social network features, such as sharing, posting, and navigation.
Check that the application is configured to support the page scrolling scenarios.
Verify that navigation between relevant modules is in accordance with the requirements.
Check to ensure that the user receives an appropriate error message, such as "Network error".
Ensure that the installed application does not consume the memory of other applications and that it enables other applications to perform satisfactorily.
If the system crashes or the application crashes, verify that it resumes from the last operation.
Ensure that the user has access to the required resources to install the application smoothly and that it will not lead to significant errors.
Testing the performance of the application in all versions of Mobile, including 2G, 3G, and 4G.
During performance testing, an application is evaluated on how well it performs and behaves under various loads. In this test, the application is continuously and steadily loaded until it reaches a threshold point (a point beyond which the application cannot withstand the load). This ensures that the application performs as expected under certain conditions like when large numbers of users access it or when a key infrastructure component such as a database server is eliminated. The most common scenarios in performance testing include: - Test the application under various load conditions to determine if it performs as expected.
EventEmitter is a Node.js class that includes all the objects that are basically capable of emitting events. This can be done by attaching named events that are emitted by the object using an eventEmitter.on() function. Thus whenever this object throws an even the attached functions are invoked synchronously.
Node.js applications run on a single processor, which means that by default they don’t take advantage of a multiple-core system. Cluster mode is used to start up multiple node.js processes thereby having multiple instances of the event loop. When we start using cluster in a nodejs app behind the scene multiple node.js processes are created but there is also a parent process called the cluster manager which is responsible for monitoring the health of the individual instances of our application.
The Thread pool is handled by the libuv library. libuv is a multi-platform C library that provides support for asynchronous I/O-based operations such as file systems, networking, and concurrency.
线程池由 libuv 库处理。libuv 是一个多平台的 C 库,提供对异步 I/O 操作的支持,例如文件系统、网络和并发。
Thread Pool
线程池
1546. What is WASI and why is it being introduced?
Web assembly provides an implementation of WebAssembly System Interface specification through WASI API in node.js implemented using WASI class. The introduction of WASI was done by keeping in mind its possible to use the underlying operating system via a collection of POSIX-like functions thus further enabling the application to use resources more efficiently and features that require system-level access.
Cluster: - There is one process on each CPU with an IPC to communicate.
集群:- 每个 CPU 上有一个进程,通过 IPC 进行通信。
In case we want to have multiple servers accepting HTTP requests via a single port, clusters can be helpful.
The processes are spawned in each CPU thus will have separate memory and node instance which further will lead to memory issues. Worker threads: - There is only one process in total with multiple threads.
工作线程:- 总共有只有一个进程,包含多个线程。
Each thread has one Node instance (one event loop, one JS engine) with most of the APIs accessible.
Shares memory with other threads (e.g. SharedArrayBuffer)
This can be used for CPU-intensive tasks like processing data or accessing the file system since NodeJS is single-threaded, synchronous tasks can be made more efficient leveraging the worker's threads.
1548. How to measure the duration of async operations?
const { PerformanceObserver, performance } = require('perf_hooks'); const obs = new PerformanceObserver((items) => { const obs = new PerformanceObserver((items) => { console.log(items.getEntries()[0].duration); console.log(items.getEntries()[0].duration); performance.clearMarks(); performance.clearMarks(); }); obs.observe({ entryTypes: ['measure'] }); obs.observe({ entryTypes: ['measure'] }); performance.measure('Start to Now'); performance.measure('Start to Now'); performance.mark('A'); performance.mark('A'); doSomeLongRunningProcess(() => { doSomeLongRunningProcess(() => { performance.measure('A to Now', 'A'); performance.measure('A to Now', 'A'); performance.mark('B'); performance.mark('B'); performance.measure('A to B', 'A', 'B'); performance.measure('A to B', 'A', 'B'); }); Additional Useful Resources 其他有用资源
NodeJS MCQ 2. Top 10 Node JS Projects Ideas 3. Node.js Vs React.js: What’s The Difference? 4. Node.js Vs Django: Which One is Better For Web Development?
API versioning is used to evolve APIs without breaking existing clients. Common approaches differ in how the version is specified. - URI versioning includes the version in the URL (for example, /v1/users). It is simple, explicit, and easy to debug, which makes it the most commonly used approach in practice.
API 版本控制用于在不破坏现有客户端的前提下演进 API。常见方法在版本指定方式上有所不同。- URI 版本控制在 URL 中包含版本(例如,/v1/users)。它简单、明确且易于调试,因此是实践中使用最广泛的方法。
Header-based versioning sends the version in a request header. It keeps URLs clean but requires clients and infrastructure to handle custom headers correctly.
Content negotiation uses the Accept header with versioned media types. It is flexible but adds complexity and is harder to reason about during debugging. In production systems, URI-based versioning is often preferred for clarity, while header-based or content negotiation approaches are used when stricter API contracts are required.
在生产系统中,基于 URI 的版本控制通常因清晰性而被优先采用,而基于头部或内容协商的方法则在需要更严格的 API 契约时使用。
1551. How do you prevent blocking the event loop when doing heavy work in an Express route?
Express runs on Node.js, which uses a single-threaded event loop. Any CPU-intensive or long-running synchronous work inside a route can block the event loop and degrade performance for all requests.
Express 运行在 Node.js 上,后者使用单线程事件循环。路由内任何 CPU 密集型或长时间运行的同步工作都可能阻塞事件循环,并降低所有请求的性能。
To prevent this: - Offload CPU-heavy tasks to worker threads or separate processes
为防止此问题:- 将高 CPU 密集任务卸载到工作线程或独立进程中
Use asynchronous, non-blocking APIs for I/O operations
Move background work to queues or job workers
Avoid synchronous loops, heavy JSON processing, or crypto operations inside routes In production systems, Express routes should remain lightweight and delegate heavy work elsewhere to maintain responsiveness.
在生产系统中,Express 路由应保持轻量级,并将繁重工作委托至其他位置,以保持响应性。
1552. How do you implement streaming responses (downloads or large payloads) in Express?
Streaming responses allow data to be sent incrementally instead of loading the entire payload into memory.
流式响应允许数据增量发送,而不是将整个负载加载到内存中。
In Express, this is typically done using Node.js streams , such as readable streams piped directly to the response.
在 Express 中,这通常通过 Node.js 流实现,例如直接将可读流通过管道连接到响应。
Common use cases include: - File downloads
常见用例包括:- 文件下载
Large exports (CSV, logs)
Proxying data from another service Streaming improves memory efficiency and enables backpressure handling. It is preferred over buffering large payloads in memory, especially for high-traffic or data-heavy endpoints.
Idempotency ensures that repeated requests produce the same result, which is critical for APIs handling payments, orders, or retries.
幂等性确保重复请求产生相同结果,这对于处理支付、订单或重试的 API 至关重要。
A common approach is: - Require clients to send an idempotency key with the request
一种常见的方法是:- 要求客户端在请求中发送幂等键
Store the key along with the request result in persistent storage
If the same key is received again, return the previous response instead of reprocessing Idempotency logic is usually implemented as middleware or service-level logic, before executing the main operation. This prevents duplicate charges or duplicate resource creation during retries or network failures.
Pagination is used to return large datasets in manageable chunks. - Offset-based pagination uses page numbers or offsets and is simple to implement, but it can become slow and inconsistent when data changes frequently.
Cursor-based pagination uses a stable reference (such as an ID or timestamp) and provides better performance and consistency for large or frequently updated datasets. In production systems: - Offset pagination is suitable for small or static datasets
在生产系统中:- 偏移量分页适合小型或静态数据集
Cursor pagination is preferred for APIs with large tables or real-time data Handling consistency involves defining clear sort order and ensuring cursors are stable and deterministic.
处理一致性涉及定义明确的排序顺序,并确保游标稳定且确定性。
1555. How do you implement graceful shutdown for an Express server?
Graceful shutdown ensures that an Express server stops accepting new requests while allowing in-flight requests to complete.
优雅关闭确保 Express 服务器停止接受新请求,同时允许正在处理的请求完成。
A typical approach includes: - Listening for shutdown signals such as SIGTERM or SIGINT
典型方法包括:- 监听关机信号,如 SIGTERM 或 SIGINT
Stopping the server from accepting new connections
Allowing active requests to finish within a timeout
Closing database connections and other resources cleanly This prevents dropped requests during deployments or restarts and is essential for zero-downtime production systems.
这可以防止部署或重启期间请求丢失,对于零停机生产系统至关重要。
1556. How do you handle centralized logging and correlation IDs across microservices?
Centralized logging collects logs from multiple services into a single searchable system, making debugging and tracing easier.
集中日志记录将来自多个服务的日志收集到一个可搜索的系统中,使调试和追踪更加容易。
Correlation IDs are used to track a single request across services by: - Generating or propagating a request ID at the edge
关联 ID 用于跨服务跟踪单个请求,方法如下:- 在边缘生成或传播请求 ID
Attaching the ID to logs, headers, and downstream calls In Express, correlation IDs are typically handled via middleware and included in all log entries. This approach helps trace failures, measure latency across services, and debug distributed systems effectively.
在 Express 中,关联 ID 通常通过中间件处理,并包含在所有日志条目中。这种方法有助于追踪故障、衡量跨服务的延迟,并有效调试分布式系统。
1557. How do you decide between cluster and worker_threads for scaling a Node service?
The choice depends on what kind of work needs to be scaled. - cluster is used to scale a Node.js service across multiple CPU cores by running multiple processes. Each process has its own event loop and memory space, making it suitable for handling more concurrent requests.
选择取决于需要扩展的工作类型。- cluster 用于通过运行多个进程来跨多个 CPU 核心扩展 Node.js 服务。每个进程都有自己的事件循环和内存空间,适合处理更多并发请求。
worker_threads are used to offload CPU-intensive tasks within the same process. They share memory and are useful for heavy computation that would otherwise block the event loop. In practice: - Use cluster for request-level concurrency and horizontal scaling
实践方面:- 使用集群实现请求级并发和水平扩展
Use worker threads for CPU-bound work that cannot be made asynchronous
1558. What are common causes of event loop blocking, and how do you detect them?
Event loop blocking happens when synchronous or long-running tasks prevent Node.js from handling other requests.
当同步或长时间运行的任务阻止 Node.js 处理其他请求时,就会发生事件循环阻塞。
Common causes include: - CPU-intensive computations
常见原因包括:- CPU密集型计算
Large synchronous loops
Heavy JSON serialization or parsing
Expensive regex operations
Blocking file system or crypto calls Detection usually involves: - Monitoring event loop delay
检测通常涉及:- 监控事件循环延迟
Observing increased request latency under load
Profiling the application to identify long-running synchronous functions This question tests whether the candidate understands how Node’s runtime behavior directly impacts application performance.
此问题测试候选者是否理解 Node 的运行时行为如何直接影响应用程序性能。
1559. How do you diagnose memory leaks in Node.js in production?
Diagnosing memory leaks in production focuses on identifying objects that keep growing and are not released.
生产环境中诊断内存泄漏的重点在于识别不断增长且未被释放的对象。
Common approaches include: - Monitoring heap usage over time to see if memory keeps increasing without stabilizing
常见方法包括:- 监控堆使用情况随时间变化,以查看内存是否持续增加而不稳定
Comparing heap snapshots taken at different intervals to find retained objects
Checking for unbounded caches, global references, event listeners, or closures
Observing garbage collection behavior, frequent or long GC cycles often indicate pressure
Correlating memory growth with specific traffic patterns or features The goal is to distinguish between expected memory usage (such as caches) and unintended object retention.
目标是区分预期内存使用(如缓存)和意外对象保留。
1560. What metrics do you monitor for Node services beyond CPU and RAM?
Queue depth or backlog for background jobs These metrics help detect performance degradation early and pinpoint whether issues are caused by the runtime, application logic, or dependencies.
这些指标有助于早期检测性能下降,并精确定位问题是由运行时、应用程序逻辑还是依赖项引起的。
1561. Explain backpressure in streams. What breaks if you ignore it?
Backpressure is the mechanism that allows a system to slow down data producers when consumers can’t keep up. In Node.js streams, it prevents memory from growing uncontrollably.
If backpressure is ignored: - Buffers keep filling up, increasing memory usage
如果忽略背压:- 缓冲区持续填满,增加内存占用
The process may experience GC pressure or crashes
Latency increases as data queues up
Downstream systems can be overwhelmed Properly handling backpressure using stream piping and respecting write() return values ensures data flows at a rate the system can safely process.
通过使用流管道并尊重 write() 的返回值来正确处理背压,确保数据以系统能安全处理的速度流动。
1562. How do you implement graceful shutdown in Node (SIGTERM) without dropping requests?
Graceful shutdown allows a Node service to stop cleanly during deploys or restarts.
优雅关闭允许 Node 服务在部署或重启时干净地停止。
A typical approach includes: - Listening for SIGTERM or SIGINT signals
典型的方法包括:- 监听 SIGTERM 或 SIGINT 信号
Stopping the server from accepting new connections
Allowing in-flight requests to complete within a timeout
Closing database connections, queues, and other resources This prevents request loss and ensures the service exits predictably, which is essential for reliable production deployments
这可以防止请求丢失,并确保服务可预测地退出,这对于可靠的生产部署至关重要。
1563. What’s your approach to zero-downtime deployments?
Strong isolation, but higher memory usage Thread-level concurrency uses worker threads within a single process. - Threads share memory and can communicate efficiently
线程级并发在单个进程内使用工作线程。线程共享内存,可以高效通信
Best suited for CPU-intensive tasks
Requires careful handling to avoid race conditions In practice, process-level concurrency is used to scale request handling, while thread-level concurrency is used to offload heavy computation.
在实际中,进程级并发用于扩展请求处理,而线程级并发用于卸载重型计算任务。
1566. How do you secure Node apps against common risks (secrets, headers, dependencies, input validation)?
Securing Node applications requires controls at multiple layers.
保护 Node 应用安全需要多层控制。
Common practices include: - Managing secrets via environment variables or secret managers, not code or repos
常见实践包括:- 通过环境变量或机密管理器管理机密信息,而非代码或仓库
Setting secure HTTP headers to protect against common attacks
Keeping dependencies updated and scanning for vulnerabilities
Validating and sanitizing all external inputs
Limiting error details exposed to clients Security is an ongoing process and must be enforced consistently across development, deployment, and runtime environments.
安全是一个持续过程,必须在开发、部署和运行时环境中一致地强制执行。
1567. How do you manage configuration safely across environments (12-factor principles)?
Managing configuration safely means keeping config separate from code and environment-specific.
安全地管理配置意味着将配置与代码及特定环境分开。
Common practices aligned with 12-factor principles include: - Using environment variables for all environment-specific settings
符合 12 因素原则的常见实践包括:- 对所有环境特定设置使用环境变量
Avoiding hard-coded secrets or environment-specific logic
Validating configuration at startup and failing fast on missing values
Using secret managers for sensitive data
Keeping configuration consistent across local, staging, and production This approach simplifies deployments and reduces configuration-related failures.
这种方法简化了部署并减少了与配置相关的故障。
1568. How do you structure a large Node monorepo (packages, shared libraries, boundaries)?
A large Node monorepo is structured to balance code reuse and isolation.
大型 Node 单体仓库的构建旨在平衡代码复用与隔离。
Common patterns include: - Organizing code into packages by domain or service
常见模式包括:- 按领域或服务将代码组织成包
Extracting shared logic into well-defined shared libraries
Enforcing clear boundaries between packages to prevent tight coupling
Using tooling to manage dependencies and versioning consistently This structure improves scalability, maintainability, and collaboration across teams working in the same repository.
The React Hook cannot be considered as a replacement for Redux (It is an open-source, JavaScript library useful in managing the application state) when it comes to the management of the global application state tree in large complex applications, even though the React will provide a useReducer hook that manages state transitions similar to Redux. Redux is very useful at a lower level of component hierarchy to handle the pieces of a state which are dependent on each other, instead of a declaration of multiple useState hooks.
In commercial web applications which is larger, the complexity will be high, so using only React Hook may not be sufficient. Few developers will try to tackle the challenge with the help of React Hooks and others will combine React Hooks with the Redux.
StrictMode is a tool added in version 16.3 of React to highlight potential problems in an application. It performs additional checks on the application.
function App() { return ( return ( <React.StrictMode> <React.StrictMode>
>
>
>
Page Content
> 页面内容
<Footer/> <Footer/>
</React.StrictMode> </React.StrictMode> ); } To enable StrictMode, tags need to be added inside the application: 要启用StrictMode,需要在应用内部添加标签:
import React from "react";
import React from "react"; import ReactDOM from "react-dom"; import ReactDOM from "react-dom"; import App from "./App"; import App from "./App"; const rootElement = document.getElementById("root"); const rootElement = document.getElementById("root"); ReactDOM.render( ReactDOM.render( <React.StrictMode> <React.StrictMode> </React.StrictMode>, </React.StrictMode>, rootElement rootElement ); StrictMode currently helps with the following issues: - Identifying components with unsafe lifecycle methods: StrictMode 目前有助于解决以下问题: - 识别使用不安全生命周期方法的组件: Certain lifecycle methods are unsafe to use in asynchronous react applications. With the use of third-party libraries, it becomes difficult to ensure that certain lifecycle methods are not used. StrictMode helps in providing us with a warning if any of the class components use an unsafe lifecycle method. - Warning about the usage of legacy string API:If one is using an older version of React, callback ref is the recommended way to manage refs instead of using the string refs. StrictMode gives a warning if we are using string refs to manage refs. 某些生命周期方法在异步 React 应用程序中使用是不安全的。由于使用第三方库,难以确保某些生命周期方法未被使用。StrictMode 帮助我们在任何类组件使用不安全生命周期方法时提供警告。 - 关于使用旧版字符串 API 的警告:如果使用较旧版本的 React,回调 ref 是管理 ref 的推荐方式,而不是使用字符串 ref。StrictMode 在我们使用字符串 ref 管理 ref 时会给出警告。
Warning about the usage of findDOMNode:Previously, findDOMNode( ) method was used to search the tree of a DOM node. This method is deprecated in React. Hence, the StrictMode gives us a warning about the usage of this method.
Warning about the usage of legacy context API (because the API is error-prone).
Reason for re-renders in React: Re-rendering of a component and its child components occur when props or the state of the component has been changed.
组件的重新渲染及其子组件的重新渲染会在组件属性(props)或状态发生变化时发生。 Re-rendering components that are not updated, affects the performance of an application. 重新渲染未更新的组件会影响应用程序的性能。
How to prevent re-rendering:
Consider the following components:
考虑以下组件: class Parent extends React.Component { class Parent extends React.Component { state = { messageDisplayed: false }; state = { messageDisplayed: false }; componentDidMount() { componentDidMount() { this.setState({ messageDisplayed: true }); this.setState({ messageDisplayed: true }); } render() { render() { console.log("Parent is getting rendered"); console.log("Parent is getting rendered"); return ( return (
>
>
); } } class Message extends React.Component { class Message extends React.Component { constructor(props) { constructor(props) { super(props); super(props); this.state = { message: "Hello, this is vivek" }; this.state = { message: "Hello, this is vivek" }; } render() { render() { console.log("Message is getting rendered"); console.log("Message is getting rendered"); return ( return (
>
{this.state.message}
>
{this.state.message}
); } }
The Parent component is the parent component and the Message is the child component. Any change in the parent component will lead to re-rendering of the child component as well. To prevent the re-rendering of child components, we use the shouldComponentUpdate( ) method:
**Note- Use shouldComponentUpdate( ) method only when you are sure that it’s a static component.
注意:只有当你确定这是一个静态组件时,才使用 shouldComponentUpdate( ) 方法。 class Message extends React.Component { class Message extends React.Component { constructor(props) { constructor(props) { super(props); super(props); this.state = { message: "Hello, this is vivek" }; this.state = { message: "Hello, this is vivek" }; } shouldComponentUpdate() { shouldComponentUpdate() { console.log("Does not get rendered"); console.log("Does not get rendered"); return false; 返回 false; } render() { render() { console.log("Message is getting rendered"); console.log("Message is getting rendered"); return ( return (
>
{this.state.message}
>
{this.state.message}
); } } As one can see in the code above, we have returned false from the shouldComponentUpdate( ) method, which prevents the child component from re-rendering. 正如在上述代码中所见,我们从 shouldComponentUpdate( ) 方法中返回了 false,这阻止了子组件重新渲染。
1572. What are the different ways to style a React component?
There are many different ways through which one can style a React component. Some of the ways are : - Inline Styling: We can directly style an element using inline style attributes. Make sure the value of style is a JavaScript object:
); } } - Using JavaScript object: We can create a separate JavaScript object and set the desired style properties. This object can be used as the value of the inline style attribute. } - 使用 JavaScript 对象:我们可以创建一个单独的 JavaScript 对象,并设置所需的样式属性。该对象可以作为内联样式属性的值。 class RandomComponent extends React.Component { class RandomComponent extends React.Component { paragraphStyles = { paragraphStyles = { color: "Red", color: "Red", fontSize: "32px" fontSize: "32px" };
); } } - CSS Stylesheet: We can create a separate CSS file and write all the styles for the component inside that file. This file needs to be imported inside the component file. } - CSS 样式表:我们可以创建一个单独的 CSS 文件,并在该文件中编写组件的所有样式。该文件需要在组件文件中导入。 import './RandomComponent.css'; import './RandomComponent.css';
There are many ways through which one can optimize the performance of a React app, let’s have a look at some of them: - Using useMemo( ) -
有多种方法可以优化 React 应用的性能,让我们看看其中一些:- 使用 useMemo() - It is a React hook that is used for caching CPU-Expensive functions. Sometimes in a React app, a CPU-Expensive function gets called repeatedly due to re-renders of a component, which can lead to slow rendering.useMemo( ) hook can be used to cache such functions. By using useMemo( ), the CPU-Expensive function gets called only when it is needed. - Using React.PureComponent - 它是一个用于缓存 CPU 密集型函数的 React 钩子。有时在 React 应用中,由于组件的重新渲染,CPU 密集型函数会被重复调用,这可能导致渲染缓慢。useMemo() 钩子可用于缓存此类函数。通过使用 useMemo(),CPU 密集型函数只在需要时被调用。- 使用 React.PureComponent - It is a base component class that checks the state and props of a component to know whether the component should be updated. Instead of using the simple React.Component, we can use React.PureComponent to reduce the re-renders of a component unnecessarily. - Maintaining State Colocation - 它是一个基类组件类,用于检查组件的状态和属性,以确定组件是否应被更新。与其使用简单的 React.Component,我们可以使用 React.PureComponent 来减少组件不必要的重新渲染。- 保持状态局部化 - This is a process of moving the state as close to where you need it as possible. Sometimes in React app, we have a lot of unnecessary states inside the parent component which makes the code less readable and harder to maintain. Not to forget, having many states inside a single component leads to unnecessary re-renders for the component. It is better to shift states which are less valuable to the parent component, to a separate component. - Lazy Loading - It is a technique used to reduce the load time of a React app. Lazy loading helps reduce the risk of web app performances to a minimum. 这是一个将状态尽可能靠近需要它的位置的过程。有时在 React 应用中,父组件内部有大量不必要的状态,这使得代码更不易读且更难维护。别忘了,在单个组件中拥有许多状态会导致组件不必要的重新渲染。最好将父组件中价值较低的状态转移到单独的组件中。- 懒加载 - 这是一种用于减少 React 应用加载时间的技术。懒加载有助于将 Web 应用性能风险降至最低。
With the help of props, we can send data from a parent to a child component.
借助 props,我们可以将数据从父组件发送到子组件。
How do we do this?
我们怎么做呢?
Consider the following Parent Component:
考虑以下父组件:
import ChildComponent from "./Child";
import ChildComponent from "./Child"; function ParentComponent(props) { function ParentComponent(props) { let [counter, setCounter] = useState(0); let [counter, setCounter] = useState(0);
let increment = () => setCounter(++counter);
let increment = () => setCounter(++counter);
return (
return (
>
>
>
); } As one can see in the code above, we are rendering the child component inside the parent component, by providing a prop called counterValue. The value of the counter is being passed from the parent to the child component. 正如上述代码所示,我们在父组件内部渲染子组件,通过提供一个名为 counterValue 的 prop。计数器的值正从父组件传递到子组件。
We can use the data passed by the parent component in the following way:
我们可以按以下方式使用由父组件传递的数据:
function ChildComponent(props) {
function ChildComponent(props) { return ( return (
>
Value of counter: {props.counterValue}
>
计数器的值:{props.counterValue}
); } We use the props.counterValue to display the data passed on by the parent component. 我们使用 props.counterValue 来显示父组件传递的数据。
Child Component to Parent Component (using callbacks)
子组件到父组件(使用回调)
This one is a bit tricky. We follow the steps below: - Create a callback in the parent component which takes in the data needed as a parameter.
这一点稍微复杂。我们遵循以下步骤:- 在父组件中创建一个回调,该回调以所需数据作为参数。
Pass this callback as a prop to the child component.
Send data from the child component using the callback. We are considering the same example above but in this case, we are going to pass the updated counterValue from child to parent.
Step1 and Step2: Create a callback in the parent component, pass this callback as a prop.
步骤1和步骤2:在父组件中创建一个回调,将这个回调作为 prop 传递。
function ParentComponent(props) {
function ParentComponent(props) { let [counter, setCounter] = useState(0); let [counter, setCounter] = useState(0); let callback = valueFromChild => setCounter(valueFromChild); let callback = valueFromChild => setCounter(valueFromChild); return ( return (
>
Value of counter: {counter}
>
计数器的值:{counter}
>
); } As one can see in the code above, we created a function called callback which takes in the data received from the child component as a parameter. 从上面的代码可以看出,我们创建了一个名为callback的函数,它将从子组件接收到的数据作为参数传入。
Next, we passed the function callback as a prop to the child component.
接下来,我们将callback函数作为属性传递给了子组件。
Step3: Pass data from the child to the parent component.
步骤3:将数据从子组件传递给父组件。
function ChildComponent(props) {
function ChildComponent(props) { let childCounterValue = props.counterValue; let childCounterValue = props.counterValue; return ( return (
>
); } In the code above, we have used the props.counterValue and set it to a variable called childCounterValue. 在上面的代码中,我们使用了props.counterValue并将其赋值给了一个名为childCounterValue的变量。
Next, on button click, we pass the incremented childCounterValue to the props.callbackFunc .
Simply put, Higher-Order Component(HOC) is a function that takes in a component and returns a new component.
简而言之,高阶组件(HOC)是一个函数,它接收一个组件并返回一个新的组件。
When do we need a Higher Order Component?
我们什么时候需要高阶组件?
While developing React applications, we might develop components that are quite similar to each other with minute differences. In most cases, developing similar components might not be an issue but, while developing larger applications we need to keep our code DRY , therefore, we want an abstraction that allows us to define this logic in a single place and share it across components. HOC allows us to create that abstraction.
); } } Notice the above components, both have similar functionality but, they are calling different methods to an API endpoint. 注意上述组件,虽然功能相似,但它们调用API端点的方式却不同。
Let’s create a Higher Order Component to create an abstraction:
让我们创建一个高阶组件来实现抽象化:
// Higher Order Component which takes a component
// 高阶组件,接收组件作为输入 // as input and returns another component // 并返回另一个组件 // "GlobalDataSource" is some global data source // "GlobalDataSource" 是某种全局数据源 function HOC(WrappedComponent, selectData) { function HOC(WrappedComponent, selectData) { return class extends React.Component { return class extends React.Component { constructor(props) { constructor(props) { super(props); super(props); this.handleChange = this.handleChange.bind(this); this.handleChange = this.handleChange.bind(this); this.state = { this.state = { data: selectData(GlobalDataSource, props), data: selectData(GlobalDataSource, props), }; } componentDidMount() { componentDidMount() { // Listens to the changes added // 监听添加的变化 GlobalDataSource.addChangeListener(this.handleChange); GlobalDataSource.addChangeListener(this.handleChange); } componentWillUnmount() { componentWillUnmount() { // Listens to the changes removed // 移除变更监听 GlobalDataSource.removeChangeListener(this.handleChange); GlobalDataSource.removeChangeListener(this.handleChange); } handleChange() { handleChange() { this.setState({ this.setState({ data: selectData(GlobalDataSource, this.props), data: selectData(GlobalDataSource, this.props), }); } render() { render() { // Rendering the wrapped component with the latest data data // 使用最新的数据渲染被包装的组件 return ; return ; } }; } We know HOC is a function that takes in a component and returns a component. 我们知道HOC是一个函数,接收一个组件并返回一个组件。
In the code above, we have created a function called HOC which returns a component and performs functionality that can be shared across both the ArticlesList component and UsersList Component.
const ArticlesListWithHOC = HOC(ArticlesList, (GlobalDataSource) => GlobalDataSource.getArticles()); const UsersListWithHOC = HOC(UsersList, (GlobalDataSource) => GlobalDataSource.getUsers()); const UsersListWithHOC = HOC(UsersList, (GlobalDataSource) => GlobalDataSource.getUsers()); Remember, we are not trying to change the functionality of each component, we are trying to share a single functionality across multiple components using HOC. 请记住,我们并不是试图改变每个组件的功能,而是使用高阶组件(HOC)在多个组件之间共享单一功能。
1576. What are the different phases of the component lifecycle?
There are four different phases in the lifecycle of React component. They are: - Initialization: During this phase, React component will prepare by setting up the default props and initial state for the upcoming tough journey.
Mounting: Mounting refers to putting the elements into the browser DOM. Since React uses VirtualDOM, the entire browser DOM which has been currently rendered would not be refreshed. This phase includes the lifecycle methods componentWillMount and componentDidMount.
Updating: In this phase, a component will be updated when there is a change in the state or props of a component. This phase will have lifecycle methods like componentWillUpdate, shouldComponentUpdate, render, and componentDidUpdate.
Unmounting: In this last phase of the component lifecycle, the component will be removed from the DOM or will be unmounted from the browser DOM. This phase will have the lifecycle method named componentWillUnmount.
React lifecycle hooks will have the methods that will be automatically called at different phases in the component lifecycle and thus it provides good control over what happens at the invoked point. It provides the power to effectively control and manipulate what goes on throughout the component lifecycle.
For example, if you are developing the YouTube application, then the application will make use of a network for buffering the videos and it consumes the power of the battery (assume only these two). After playing the video if the user switches to any other application, then you should make sure that the resources like network and battery are being used most efficiently. You can stop or pause the video buffering which in turn stops the battery and network usage when the user switches to another application after video play.
So we can say that the developer will be able to produce a quality application with the help of lifecycle methods and it also helps developers to make sure to plan what and how to do it at different points of birth, growth, or death of user interfaces.
The various lifecycle methods are: - constructor(): This method will be called when the component is initiated before anything has been done. It helps to set up the initial state and initial values.
getDerivedStateFromProps(): This method will be called just before element(s) rendering in the DOM. It helps to set up the state object depending on the initial props. The getDerivedStateFromProps() method will have a state as an argument and it returns an object that made changes to the state. This will be the first method to be called on an updating of a component.
render(): This method will output or re-render the HTML to the DOM with new changes. The render() method is an essential method and will be called always while the remaining methods are optional and will be called only if they are defined.
componentDidMount(): This method will be called after the rendering of the component. Using this method, you can run statements that need the component to be already kept in the DOM.
shouldComponentUpdate(): The Boolean value will be returned by this method which will specify whether React should proceed further with the rendering or not. The default value for this method will be True.
getSnapshotBeforeUpdate(): This method will provide access for the props as well as for the state before the update. It is possible to check the previously present value before the update, even after the update.
componentDidUpdate(): This method will be called after the component has been updated in the DOM.
componentWillUnmount(): This method will be called when the component removal from the DOM is about to happen.
Static typing refers to the process of code check during the time of compilation for ensuring all variables will be statically typed. React Hooks are functions that are designed to make sure about all attributes must be statically typed. For enforcing stricter static typing within our code, we can make use of the React API with custom Hooks.
Built-in Hooks: The built-in Hooks are divided into 2 parts as given below:
Basic Hooks:
useState(): This functional component is used to set and retrieve the state.
useState():此功能组件用于设置和检索状态。 useEffect(): It enables for performing the side effects in the functional components. useEffect():它允许在功能组件中执行副作用。
useContext(): It is used for creating common data that is to be accessed by the components hierarchy without having to pass the props down to each level. - Additional Hooks:
useContext():它用于创建公共数据,这些数据可供组件层次结构访问,而无需将属性传递给每一级。 - 额外的Hooks: useReducer() : It is used when there is a complex state logic that is having several sub-values or when the upcoming state is dependent on the previous state. It will also enable you to optimization of component performance that will trigger deeper updates as it is permitted to pass the dispatch down instead of callbacks. useReducer():当存在具有多个子值的复杂状态逻辑,或者即将到来的状态依赖于先前状态时使用它。它还允许您优化触发更深层更新的组件性能,因为可以将分派(dispatch)传递给下方而不是回调。
useMemo() : This will be used for recomputing the memoized value when there is a change in one of the dependencies. This optimization will help for avoiding expensive calculations on each render.
useCallback() : This is useful while passing callbacks into the optimized child components and depends on the equality of reference for the prevention of unneeded renders.
useRef() : It will permit creating a reference to the DOM element directly within the functional component.
useRef():它允许在函数组件内直接创建对 DOM 元素的引用。
useLayoutEffect(): It is used for the reading layout from the DOM and re-rendering synchronously.
useLayoutEffect():用于从 DOM 中读取布局并同步重新渲染。
Custom Hooks: A custom Hook is basically a function of JavaScript. The Custom Hook working is similar to a regular function. The “use” at the beginning of the Custom Hook Name is required for React to understand that this is a custom Hook and also it will describe that this specific function follows the rules of Hooks. Moreover, developing custom Hooks will enable you for extracting component logic from within reusable functions.
React Hooks will avoid a lot of overheads such as the instance creation, binding of events, etc., that are present with classes.
Hooks in React will result in smaller component trees since they will be avoiding the nesting that exists in HOCs (Higher Order Components) and will render props which result in less amount of work to be done by React.
1582. Do Hooks cover all the functionalities provided by the classes?
Our goal is for Hooks to cover all the functionalities for classes at its earliest. There are no Hook equivalents for the following methods that are not introduced in Hooks yet: - getSnapshotBeforeUpdate()
componentDidCatch() Since it is an early time for Hooks, few third-party libraries may not be compatible with Hooks at present, but they will be added soon.
React Router refers to the standard library used for routing in React. It permits us for building a single-page web application in React with navigation without even refreshing the page when the user navigates. It also allows to change the browser URL and will keep the user interface in sync with the URL. React Router will make use of the component structure for calling the components, using which appropriate information can be shown. Since React is a component-based framework, it’s not necessary to include and use this package. Any other compatible routing library would also work with React.
The major components of React Router are given below: - BrowserRouter: It is a router implementation that will make use of the HTML5 history API (pushState, popstate, and event replaceState) for keeping your UI to be in sync with the URL. It is the parent component useful in storing all other components.
Routes: It is a newer component that has been introduced in the React v6 and an upgrade of the component.
Route: It is considered to be a conditionally shown component and some UI will be rendered by this whenever there is a match between its path and the current URL.
Link: It is useful in creating links to various routes and implementing navigation all over the application. It works similarly to the anchor tag in HTML.
Conditional rendering refers to the dynamic output of user interface markups based on a condition state. It works in the same way as JavaScript conditions. Using conditional rendering, it is possible to toggle specific application functions, API data rendering, hide or show elements, decide permission levels, authentication handling, and so on.
There are different approaches for implementing conditional rendering in React. Some of them are: - Using if-else conditional logic which is suitable for smaller as well as for medium-sized applications
I will assume that you are having some coding knowledge about JavaScript and have installed Node on your system for creating a below given React Hook program. An installation of Node comes along with the command-line tools: npm and npx, where npm is useful to install the packages into a project and npx is useful in running commands of Node from the command line. The npx looks in the current project folder for checking whether a command has been installed there. When the command is not available on your computer, the npx will look in the npmjs.com repository, then the latest version of the command script will be loaded and will run without locally installing it. This feature is useful in creating a skeleton React application within a few key presses.
Open the Terminal inside the folder of your choice, and run the following command:
在你选择的文件夹中打开终端,然后运行以下命令:
npx create-react-app react-items-with-hooks
npx create-react-app react-items-with-hooks Here, the create-react-app is an app initializer created by Facebook, to help with the easy and quick creation of React application, providing options to customize it while creating the application? The above command will create a new folder named react-items-with-hooks and it will be initialized with a basic React application. Now, you will be able to open the project in your favourite IDE. You can see an src folder inside the project along with the main application component App.js . This file is having a single function App() which will return an element and it will make use of an extended JavaScript syntax(JSX) for defining the component. 在这里,create-react-app 是由 Facebook 创建的应用程序初始化器,用于帮助快速轻松地创建 React 应用程序,并在创建应用程序时提供自定义选项。上述命令将创建一个名为 react-items-with-hooks 的新文件夹,并使用一个基本的 React 应用程序对其进行初始化。现在,你可以在你喜欢的 IDE 中打开该项目。你可以看到项目内有一个 src 文件夹,以及主应用程序组件 App.js。该文件有一个单一的函数 App(),它返回一个元素,并使用扩展的 JavaScript 语法(JSX)来定义组件。
JSX will permit you for writing HTML-style template syntax directly into the JavaScript file. This mixture of JavaScript and HTML will be converted by React toolchain into pure JavaScript that will render the HTML element.
JSX 允许你直接在 JavaScript 文件中编写 HTML 风格的模板语法。这种 JavaScript 和 HTML 的混合内容将由 React 工具链转换为纯 JavaScript,从而渲染 HTML 元素。
It is possible to define your own React components by writing a function that will return a JSX element. You can try this by creating a new file src/SearchItem.js and put the following code into it.
import React from 'react'; export function SearchItem() { export function SearchItem() { return ( return (
>
>
>
Search Results
搜索 结果
>
>
>
>
Item Name
>
条目名称
Price
>
价格
Quantity
>
数量
>
>
>
>
); } This is all about how you can create a component. It will only display the empty table and doesn’t do anything. But you will be able to use the Search component in the application. Open the file src/App.js and add the import statement given below to the top of the file. 这就是关于如何创建组件的全部内容。它只会显示空表格,不会执行任何操作。但你将能够在应用程序中使用搜索组件。打开文件 src/App.js,并在文件顶部添加下面给出的导入语句。
import { SearchItem } from './SearchItem';
import { SearchItem } from './SearchItem'; Now, from the logo.svg, import will be removed and then contents of returned value in the function App() will be replaced with the following code: 现在,将从logo.svg中移除导入,然后函数App()中返回值的內容将被替换为以下代码:
>
>
Items with Hooks
> 使用Hooks的条目
>
>
You can notice that the element has been used just similar to an HTML element. The JSX syntax will enable for including the components in this approach directly within the JavaScript code. Your application can be tested by running the below-given command in your terminal. 你可以注意到,该元素的使用方式与HTML元素类似。JSX语法将支持以这种方式直接在JavaScript代码中包含组件。你可以通过在终端中运行下面给出的命令来测试你的应用程序。
npm start
npm start This command will compile your application and open your default browser into http://localhost:4000 . This command can be kept on running when code development is in progress to make sure that the application is up-to-date, and also this browser page will be reloaded each time you modify and save the code. 此命令将编译你的应用程序,并在默认浏览器中打开http://localhost:4000 。在代码开发进行期间,可以保持此命令运行,以确保应用程序是最新的,并且每次你修改并保存代码时,此浏览器页面都会重新加载。
This application will work finely, but it doesn’t look nice as it doesn’t react to any input from the user. You can make it more interactive by adding a state with React Hooks, adding authentication, etc.
A switching component refers to a component that will render one of the multiple components. We should use an object for mapping prop values to components.
切换组件是指一种会渲染多个组件之一的组件。我们应该使用一个对象来将prop值映射到组件。
A below-given example will show you how to display different pages based on page prop using switching component:
下面给出的示例将展示如何使用切换组件根据page prop显示不同的页面:
import HomePage from './HomePage'
import HomePage from './HomePage' import AboutPage from './AboutPage' import AboutPage from './AboutPage' import FacilitiesPage from './FacilitiesPage' import FacilitiesPage from './FacilitiesPage' import ContactPage from './ContactPage' import ContactPage from './ContactPage' import HelpPage from './HelpPage' import HelpPage from './HelpPage' const PAGES = { const PAGES = { home: HomePage, home: HomePage, about: AboutPage, about: AboutPage, facilitiess: FacilitiesPage, facilitiess: FacilitiesPage, contact: ContactPage contact: ContactPage help: HelpPage help: HelpPage } const Page = (props) => { const Page = (props) => { const Handler = PAGES[props.page] || HelpPage const Handler = PAGES[props.page] || HelpPage return 返回 } // The PAGES object keys can be used in the prop types for catching errors during dev-time. // PAGES 对象的键可用于属性类型中,以便在开发时捕获错误。 Page.propTypes = { Page.propTypes = { page: PropTypes.oneOf(Object.keys(PAGES)).isRequired page: PropTypes.oneOf(Object.keys(PAGES)).isRequired }
1587. How to re-render the view when the browser is resized?
It is possible to listen to the resize event in componentDidMount() and then update the width and height dimensions. It requires the removal of the event listener in the componentWillUnmount() method.
In the code given below, we have a Parent component AppDemo.js and have two Child Components HomePage and AboutPage . Everything is kept inside a Router by using React-router Route. It is also having a route for /about/{params} where we will pass the data.
import React, { Component } from ‘react’; class AppDemo extends Component { class AppDemo extends Component { render() { render() { return ( return (
>
>
>
Home
> Home
>
>
About
> About
>
>
>
>
>
>
); } } export default AppDemo; export default AppDemo; The HomePage is a functional component with a button. On button click, we are using props.history.push(‘/about/’ + data) to programmatically navigate into /about/data . HomePage 是一个带有按钮的函数式组件。点击按钮时,我们使用 props.history.push('/about/' + data) 以编程方式导航到 /about/data。
handleClick('DemoButton')}>To About
> handleClick('DemoButton')}>To About
) } Also, the functional component AboutPage will obtain the data passed by props.match.params.aboutId . 此外,函数式组件 AboutPage 将获取通过 props.match.params.aboutId 传递的数据。
export default function AboutPage(props) {
export default function AboutPage(props) { if(!props.match.params.aboutId) { if(!props.match.params.aboutId) { return
No Data Yet
return
No Data Yet
} return ( return (
>
{`Data obtained from HomePage is ${props.match.params.aboutId}`}
> {`Data obtained from HomePage is ${props.match.params.aboutId}`}
) } After button click in the HomePage the page will look like below: 在 HomePage 中点击按钮后,页面将如下所示:
1589. How to perform automatic redirect after login?
The react-router package will provide the component in React Router. Rendering of a component will navigate to a newer location. In the history stack, the current location will be overridden by the new location just like the server-side redirects.
import React, { Component } from 'react' import { Redirect } from 'react-router' import { Redirect } from 'react-router' export default class LoginDemoComponent extends Component { export default class LoginDemoComponent extends Component { render() { render() { if (this.state.isLoggedIn === true) { 如果(this.state.isLoggedIn === true){ return return } else { } else { return
{'Please complete login'}
return
{'请完成登录'}
} } } Conclusion 结论 React has got more popularity among the top IT companies like Facebook, PayPal, Instagram, Uber, etc., around the world especially in India. Hooks is becoming a trend in the React community as it removes the state management complexities. React 在全球顶级 IT 公司(如 Facebook、PayPal、Instagram、Uber 等)中越来越受欢迎,尤其是在印度。Hooks 正在成为 React 社区的一种趋势,因为它消除了状态管理的复杂性。
This article includes the most frequently asked ReactJS and React Hooks interview questions and answers that will help you in interview preparations. Also, remember that your success during the interview is not all about your technical skills, it will also be based on your state of mind and the good impression that you will make at first. All the best!!
The primary reason and an important one why well-built native apps feel so smooth are by avoiding expensive operations during interactions and animations. React Native has a limitation that there is only a single JS execution thread, but you can use InteractionManager to make sure long-running work is scheduled to start after any interactions/animations have completed.
It is sometimes necessary to make changes directly to a component without using state/props to trigger a re-render of the entire subtree. When using React in the browser, for example, you sometimes need to directly modify a DOM node, and the same is true for views in mobile apps. setNativeProps is the React Native equivalent to setting properties directly on a DOM node. Use setNativeProps when frequent re-rendering creates a performance bottleneck. Direct manipulation will not be a tool that you reach for frequently; you will typically only be using it for creating continuous animations to avoid the overhead of rendering the component hierarchy and reconciling many views. setNativeProps is imperative and stores state in the native layer (DOM, UIView, etc.) and not within your React components, which makes your code more difficult to reason about. Before you use it, try to solve your problem with setState and shouldComponentUpdate.
有时需要直接对组件进行更改,而无需使用状态或属性来触发整个子树的重新渲染。例如,在浏览器中使用 React 时,有时需要直接修改 DOM 节点,这在移动应用中的视图上也是如此。setNativeProps 是 React Native 中直接设置 DOM 节点属性的等价物。当频繁重新渲染造成性能瓶颈时,请使用 setNativeProps。直接操作不会是你经常使用的工具;通常只会用它来创建连续动画,以避免渲染组件层级和协调多个视图的开销。setNativeProps 是命令式的,它在原生层(DOM、UIView 等)中存储状态,而不是在你的 React 组件内,这使得你的代码更难推理。在使用它之前,请尝试用 setState 和 shouldComponentUpdate 解决你的问题。
SSL (Secure Sockets Layer) and its successor, TLS (Transport Layer Security), are protocols for establishing authenticated and encrypted links between networked computers. SSL/TLS works by binding the identities of entities such as websites and companies to cryptographic key pairs via digital documents known as X.509 certificates. Each key pair consists of a private key and a public key. The private key is kept secure, and the public key can be widely distributed via a certificate. Understanding of pinning Pinning is an optional mechanism that can be used to improve the security of a service or site that relies on SSL Certificates. Pinning allows specifying a cryptographic identity that should be accepted by users visiting site/app Why do we need SSL pinning?
One of the inherent risks to the SSL ecosystem is mis-issuance. This is when an unauthorized certificate is issued for a domain/host you control. This can happen with both public and private PKIs (Public Key Infrastructure)
How is SSL pinning used in Mobile applications? When mobile applications communicate with the server, they typically use SSL to protect the transmitted data against tampering. By default SSL implementations used, apps trust any server with a certificate trusted by the Operating systems trust store, This store is a list of certificate authorities that are shipped with the operating system.
With SSL pinning, however, the application is configured to reject all but one or few predefined certificates, whenever the application connects to a server, it compares the server certificate with the pinned certificate(s) , if and only if they match the server is trusted and SSL connection is established.
iOS - Keychain Services Keychain Services allows you to securely store small chunks of sensitive info for the user. This is an ideal place to store certificates, tokens, passwords, and any other sensitive information that doesn’t belong in Async Storage. Android - Secure Shared Preferences# Shared Preferences is the Android equivalent for a persistent key-value data store. Data in Shared Preferences is not encrypted by default, but Encrypted Shared Preferences wraps the Shared Preferences class for Android, and automatically encrypts keys and values. Android - Keystore The Android Keystore system lets you store cryptographic keys in a container to make it more difficult to extract from the device. In order to use iOS Keychain services or Android Secure Shared Preferences, you can either write a bridge yourself or use a library that wraps them for you and provides a unified API at your own risk. Some libraries to consider: - Expo-secure-store
react-native-sensitive-info - secure for iOS, but uses Android Shared Preferences for Android (which is not secure by default). There is however a branch that uses Android Keystore.
1594. Describe Memory leak Issue in React Native , how can it be detected and resolved ?
In JavaScript memory is managed automatically by Garbage Collector (GC). In short, Garbage Collector is a background process that periodically traverses the graph of allocated objects and their references. If it happens to encounter a part of the graph that is not being referenced directly or indirectly from root objects (e.g., variables on the stack or a global object like window or navigator) that whole part can be deallocated from the memory. In React Native world each JS module scope is attached to a root object. Many modules, including React Native core ones, declare variables that are kept in the main scope (e.g., when you define an object outside of a class or function in your JS module). Such variables may retain other objects and hence prevent them from being garbage collected. Some Causes of Memory Leak: - Unreleased timers/listeners added in componentDidMount
Closure scope leaks Detecting memory leaks for IOS: In Xcode, Go to XCode → Product → Profile (⌘ + i) After that shows you all templates choose leaks. Detecting memory leaks for Android : Run React Native app normally (react-native run-android) Run Android Studio On the menu, click Tools → Android → Enable ADB Integration Click Tools → Android → Android Device Monitor When Android Device Monitor shows up, click Monitor → Preferences There is also one more way in Android Perf Monitor (Performance Monitor) is a good choice to use for android leak monitoring.
Use Proguard to minimize the application size.(It does this by stripping parts of the React Native Java bytecode (and its dependencies) that your app is not using)
Create reduced-sized APK files for specific CPU architectures. When you do that, your app users will automatically get the relevant APK file for their specific phone’s architecture. This eliminates the need to keep JSCore binaries that support multiple architectures and consequently reduces the app size.
Compress images and other graphic elements. Another option to reduce image size is using file types like APNG in place of PNG files.
Don’t store raw JSON data, eIther we need to Compress it or convert it into static object IDs.
Optimize native libraries.
Optimize the number of state operations and remember to use pure and memoized components when needed
Use Global State wisely for example worst-case scenario is when state change of single control like TextInput or CheckBox propagates render of the whole application. Use libraries like Redux or Overmind.js to handle your state management in a more optimized way.
Use key attribute on list items, it helps React Native to pick which list to update when rendering a long list of data
Use VirtualizedList, FlatList, and SectionList for large data sets.
Clear all the active timers which may lead to heavy memory leakage issues.
1596. What’s the real cause behind performance issues in React Native ?
The real cause behind React Native performance issues is that each thread (i.e Native and JS thread) is blazingly fast. The performance bottleneck in React Native app occurs when you’re passing the components from one thread to another unnecessarily or more than required. A major thumb rule to avoid any kind of performance-related issue in React Native is to keep the passes over the bridge to a minimum. - Native thread built for running Java/ Kotlin, Swift/ Objective C
The typical data flow in Redux starts with a call back from the User Interface component which dispatches an action with a payload. After that, the reducers intercept and receive the dispatched actions, generating a new application state. After that, the actions are propagated down through a hierarchy of components from the Redux store.
Redux 中的典型数据流始于用户界面组件的回调,该回调会分发一个带有负载的 action。之后,reducers 拦截并接收分发的 actions,生成新的应用程序状态。然后,actions 从 Redux store 沿组件层级向下传播。
Redux Saga functions as a separate thread in our programme which is solely responsible for side effects. Redux Saga is a redux middleware. In other words, it means that it can be started, paused, and aborted from the main application using standard Redux actions, has access to the entire Redux application state, and can also dispatch Redux actions.
“Store” in Redux is used to carry together all the states, reducers, and actions which create the app. Some of the responsibilities of the store are as follows: - The state of the current application from inside is held by the Redux Store.
Redux 中的“store”用于汇集组成应用程序的所有状态、reducers 和 actions。store 的一些职责如下:- 当前应用程序的内部状态由 Redux Store 持有。
We can access the current state using store.getState().
We can update the state using store.dispatch(action).
We can also register listener callbacks using the store.subscriber(listener).
Using Redux Thunk middleware, we can write action creators returning a function instead of an action. This thunk can postpone the dispatch of an action, or do conditional dispatchment. The arguments passed to the inner function are the store methods dispatch and getState(). In the event of an action creator returning a function, the function gets executed by the Redux Thunk middleware and it does not have to be pure. In other words, the function is allowed to have side effects, including executing asynchronous API calls. It can even dispatch actions. Redux thunk is used to delay the dispatch of an action, or to dispatch in the event of a certain condition being met. At the time of dispatch of a function instead of an action object, if Redux Thunk middleware is enabled, the middleware will call that function with the dispatch method itself as the first argument.
In order to use connect from React Redux, we will have to follow a couple of steps to use our store in our container: - Firstly, we use the mapStateToProps(): This would map the state variables from our store to the props which we specify.
Secondly, we connect the above props to our container: The object returned by the mapStateToProps component is connected to the container. A sample code for connect from react-redux is given below:
以下是来自 react-redux 的 connect 示例代码:
import React from 'react';
import React from 'react'; import { connect } from 'react-redux'; import { connect } from 'react-redux';
class App extends React.Component {
class App extends React.Component { render() { render() { return
Redux Forms present in React and Redux help in enabling a form in React to use Redux for storing all of its states. They can be used with raw inputs in HTML5. Redux forms work extremely well with User Interface (UI) frameworks, for instance, Material UI, React Widgets, React Bootstrap and many more.
Every Redux application has multiple top-level directories as given below: - Components: Components are used for “dumb” React components unfamiliar with Redux.
For accessing a redux store outside a react component, we can export the store from the module where it has been created with createStore as done in the following example:
The key differences in the comparison: Context Api vs Redux are as follows:
React Redux与Context API之间比较的关键区别如下:
React Redux
React Context API
In order to use React-Redux in our application, we need to code it separately and then merge it into the main project. 为了在我们的应用中使用React-Redux,我们需要单独编写它,然后将其合并到主项目中。
React Context can be used in the application directly. React Context可以直接在应用中使用。
The number of features provided by React-Redux is comparatively more than React Context. React-Redux提供的功能数量相对多于React Context。
The number of features provided by React Context is comparatively less than React-Redux. React Context提供的功能数量相对少于React-Redux。
1611. What do you understand about the Redux Saga?
Redux Saga is a middleware library that can be useful for allowing a Redux store to interact with the resources outside of itself in an asynchronous manner, for example, making HTTP requests to external services, accessing browser storage, executing Input/Output operations and many more. These operations are also called side effects.
In order to add multiple middlewares to Redux, the usage of applyMiddleware can do the work. In applyMiddleware, we can pass every piece of middleware as a new argument. Therefore, our job is to just pass each piece of middleware that we want. In the example given below, we have added Redux Thunk and logger middlewares as an argument:
import { createStore, applyMiddleware } from 'redux'
import { createStore, applyMiddleware } from 'redux' const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore); const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore); Conclusion 结论 The purpose of this article was to explain to our readers what Redux actually is, what is it used for and what are the most important questions asked in the interviews. It is one of the most important JavaScript libraries which is being used alongside React for building a number of applications seamlessly and therefore, we would suggest that any budding talent of today should be familiar with the concepts of Redux to get an edge over others. 本文旨在向读者解释Redux究竟是什么、它的用途以及面试中最常被问到的问题。Redux是与React一同使用的最重要的JavaScript库之一,用于无缝构建大量应用程序,因此,我们建议当今任何有抱负的人才都应熟悉Redux的概念,以获得竞争优势。
Given below are some of the references and recommended resources to learn more about Redux: - Redux Documentation and API usages
以下是进一步学习Redux的一些参考资料和推荐资源:- Redux文档和API用法
Redux Github
For using Redux with Node Package Manager - NPM
React
Angular
1614. What do you understand about Grand Central Dispatch (GDC)?
GCD (Grand Central Dispatch) is a low-level API for controlling several operations at the same time. This notion is employed to aid in the enhancement of application performance. This procedure is used to handle numerous jobs at once. The most relevant API for multitasking with Async and Sync programming in iOS is Grand Central Dispatch (GCD). - Dispatch Queue: The task is managed in FIFO (First In First Out) order by the Dispatch Queue. Dispatch queues are thread-safe because they can be accessed by several threads at the same time.
GCD(Grand Central Dispatch)是一个用于同时控制多个操作的低级 API。此概念被用来帮助提升应用程序的性能。此过程用于同时处理众多任务。在 iOS 中使用异步和同步编程进行多任务处理时,最相关的 API 是 Grand Central Dispatch (GCD)。- 派发队列:任务由派发队列按 FIFO(先进先出)顺序管理。派发队列是线程安全的,因为它们可被多个线程同时访问。
Concurrent: This process has started numerous tasks at the same time but does not know when they will finish. It can be completed in whatever sequence you want. They perform one or more things concurrently at the same time. The work is finished in the order in which it was queued, not in the order in which it was completed.
Serial: A single task will be executed at a time. It is possible to use it to synchronize access to a certain resource.
Sync: After the work is completed, a synchronous function returns control to the caller.
Asynchronous: An asynchronous function returns instantly after ordering a job to begin but does not wait for it to finish.
1615. State your understanding of delegates in ios Swift.
Delegate, in ios Swift, is a design pattern that allows data or communication to be passed across structs or classes. Delegate allows one object to deliver a message to another when a certain event occurs, and it is used to handle table and collection view events. Delegates have a one on one interaction and communicate with one another.
在 iOS Swift 中,委托是一种设计模式,允许在结构体或类之间传递数据或通信。委托允许一个对象在特定事件发生时向另一个对象传递消息,并且它被用来处理表格和集合视图事件。委托具有一对一交互,并相互通信。
An example of a delegate is given below:
委托的一个示例如下:
// Defining a custom delegate known as SeeActionDelegate
// 定义自定义委托,称为 SeeActionDelegate protocol SeeActionDelegate { protocol SeeActionDelegate { // Defining the required delegate variables // 定义所需的委托变量 var state: GetState { get } var state: GetState { get } var userIdentity: String? { get set } var userIdentity: String? { get set } // Defining the required delegate blocks // 定义所需的委托块 var errorHandler: ((Error) -> Void)? { get set } var errorHandler: ((Error) -> Void)? { get set } // Defining the required delegate functions // 定义所需的委托函数 func handle(action: GetAction) func handle(action: GetAction) } The enums used in the above delegate are: 上述委托中使用的枚举是:
enum GetState {
enum GetState { case default case default case loading case loading } enum GetAction { enum GetAction { case saved case saved case canceled case canceled }
1616. How can the double question mark symbol "??" be used in ios Swift programming?
The nil-coalescing operator "??" is a shorthand for the ternary conditional operator, which we used to test for nil. A double question mark can also be used to set a variable's default value.
When one or more conditions are not met, a GUARD statement is used to transfer program control out of the scope. This remark aids in avoiding the doomsday pyramid. The following is the syntax of a GUARD statement:
Generics are a way to avoid code duplication. It is usual to repeat a method that takes one type of parameter to accommodate a parameter of a different type. Generics can be used in both functions and data types in Swift, such as classes, structures, and enumerations.
泛型是一种避免代码重复的方式。通常,为了适应不同类型的参数,会重复编写接受一种参数类型的方法。在 Swift 中,泛型可以用于函数和数据类型,如类、结构和枚举。
func integerEquality(_ a: Int, _ b: Int) -> Bool { return a == b return a == b } func stringEquality(_ a: String, _ b: String) -> Bool { func stringEquality(_ a: String, _ b: String) -> Bool { return a == b return a == b } stringEquality("hello", "hello") // returns true stringEquality("hello", "hello") // 返回 true integerEquality(5, 5) // returns true integerEquality(5, 5) // 返回 true For example, the second function in the above code is a "clone" of the first, but it accepts texts rather than numbers. 例如,上述代码中的第二个函数是第一个函数的“克隆”,但它接受文本而不是数字。
func commonEquality<T: Equatable>(_ a: T, _ b: T) -> Bool { return a == b return a == b } commonEquality("hello", "hello") // returns true commonEquality("hello", "hello") // 返回 true commonEquality(5, 5) // returns true commonEquality(5, 5) // 返回 true You can consolidate the two functions into one and maintain type safety at the same time by using generics. Given above is the way to do it in general. 通过使用泛型,你可以将两个函数合并为一个,同时保持类型安全。上面给出的是实现这一目标的一般方法。
Because you are testing equality here, you can use any type that implements the Equatable protocol as a parameter. This code achieves the desired outcome while preventing the use of non-typed parameters.
An optional, in ios Swift, allows any type of variable to reflect a lack of value. The absence of value in Objective C is only available in reference types that use the nil special value. This is not possible with value types like int or float.
在 iOS Swift 中,可选值允许任何类型的变量反映值的缺失。在 Objective-C 中,值的缺失仅适用于使用 nil 特殊值的引用类型。这对于像 int 或 float 这样的值类型是不可能的。
With optionals, ios Swift extends the absence of value ideas to both reference and value types. An optional variable can be set to either a value or nil, which indicates that it has no value. An example of an optional is given below:
通过可选值,iOS Swift 将值的缺失概念扩展到引用类型和值类型。可选变量可以设置为一个值或 nil,这表示它没有值。下面给出了一个可选值的示例:
var text: String?
var text: String? text = "I will go to school." text = "我将去学校。" print(text) print(text)
1620. What are a few scenarios in which we can't avoid using implicitly unwrapped optionals and why so?
The following are the most prevalent reasons for using implicitly unwrapped optionals: - When you can't initialise a property that is not nil (absence of value) by definition at the moment of instantiation. An Interface Builder outlet, for example, is always initialised after its owner. In this case, you have ensured that the outlet is non-nil before using it, provided it's properly configured in Interface Builder.
To tackle the problem of a strong reference cycle, which occurs when two instances refer to each other and one of them requires a non-nil reference to the other. In this situation, one side of the reference is marked as unowned, while the other employs an implicitly unwrapped optional.
1621. In Swift, how would you describe a circular reference? What are your options for resolving it?
When two instances have a strong connection to one other, a circular reference occurs, resulting in a memory leak because neither of the two instances will ever be deallocated. The reason for this is that you can't deallocate an instance if it has a strong reference to it, yet each instance maintains the other alive due to the strong reference. This might lead to a deadlock which is extremely bad for the application.
Breaking the strong circular reference by replacing one of the strong references with a weak or unowned reference would fix the problem of a circular reference.
Apple's Core Data framework is one of the most powerful frameworks for macOS and iOS programmes. In our applications, core data is used to manage the model layer object. Within iOS applications, we may use Core Data as a framework to filter, alter, save, and track data. Core Data is not a relational database in the traditional sense. Without learning SQL, we can easily connect the objects in our app to the table records in the database using core data. The M in the MVC structure stands for core data.
Apple 的 Core Data 框架是 macOS 和 iOS 程序中最强大的框架之一。在我们的应用程序中,Core Data 用于管理模型层对象。在 iOS 应用程序内,我们可以使用 Core Data 作为框架来过滤、修改、保存和跟踪数据。Core Data 不是传统意义上的关系数据库。无需学习 SQL,我们可以使用 Core Data 轻松地将应用中的对象与数据库中的表记录连接起来。MVC 结构中的 M 代表 Core Data。
Some features of Core data are listed below: - Integration with the iOS and macOS toolchains is seamless.
Core Data 的一些特性如下:- 与 iOS 和 macOS 工具链的集成是无缝的。
Data organisation, filtering, and grouping in memory and in the user interface (User Interface).
Object storage is supported automatically.
Property values are validated automatically.
The first object graph management framework.
The object graph's life cycle is managed using the Core Data framework.
1623. What are the several methods for unwrapping an optional in Swift?
The several methods for unwrapping an optional in Swift are as follows: - Forced unwrapping: It consists in adding a ! after an Optional value, to automatically unwrap it, without having to check whether it is nil or not. Example - let v:String = b!Optional chaining: The technique of querying and calling properties, methods, and subscripts on an optional that is currently nil is known as optional chaining. The property, method, or subscript call succeeds if the optional includes a value; if the optional is nil, the property, method, or subscript call returns nil. Multiple inquiries can be chained together, and if any link in the chain is nil, the entire chain will fail gracefully. Example -
在 Swift 中解包可选类型的几种方法如下: - 强制解包:在可选值后添加一个 !,自动解包它,而无需检查它是否为 nil。示例 - let v:String = b!可选链:在当前为 nil 的可选类型上查询和调用属性、方法和下标的技术称为可选链。如果可选类型包含值,则属性、方法或下标调用成功;如果可选类型为 nil,则属性、方法或下标调用返回 nil。多个查询可以链式连接,如果链中任何一环为 nil,整个链将优雅地失败。示例 - let v = b?.count - Nil coalescing operator: If there is a value inside an optional, the nil coalescing operator unwraps it and returns it. If no value is provided – for example, if the optional is nil – a default value is used instead. The result will not be optional in either case: it will be either the value from within the optional or the default value used as a backup. Example - let v = b?.count - 空合并运算符:如果可选类型内有值,空合并运算符会解包并返回该值。如果没有提供值——例如,如果可选类型为 nil——则使用默认值作为替代。结果在任一情况下都不是可选的:它要么是可选类型中的值,要么是作为后备的默认值。示例 - let v = b ?? "" - Optional pattern: An optional pattern matches items wrapped in an Optional enumeration's some(Wrapped) case. Optional patterns appear in the same places as enumeration case patterns and consist of an identifier pattern followed by a question mark. An example is given below: let v = b ?? "" - 可选模式:可选模式匹配可选枚举的 some(Wrapped) 情形中的项目。可选模式出现在与枚举情形模式相同的位置,并由标识符模式后跟问号组成。下面给出一个示例: if case let v? = b { if case let v? = b { print(v) print(v) } - Guard statement: When certain requirements are not met, the guard statement in Swift is used to shift program control out of scope. With one key exception, the guard statement is comparable to the if statement. When a given condition is met, the if statement is executed. The guard statement, on the other hand, is executed when a given condition is not met. Example is given below: } - Guard 语句:当某些要求未满足时,Swift 中的 guard 语句用于将程序控制移出作用域。除一个关键例外外,guard 语句与 if 语句类似。当给定条件满足时,if 语句被执行。而 guard 语句则在给定条件未满足时被执行。下面给出示例: guard let v = b else { guard let v = b else { return return } - Optional binding: Optional binding is used to determine whether or not an optional has a value. If it does have a value, unwrap it and save it in a temporary variable or constant. Example is given below: } - 可选绑定:可选绑定用于确定可选类型是否有值。如果有值,则解包它并将其保存在临时变量或常量中。下面给出示例: if let v = b { if let v = b { print("b has been unwrapped with success and is = (v)") print("b 已成功解包,且等于 (v)") } - Implicitly unwrapped variable declaration: Because a variable may start life as nil, but will always have a value before you need to use it, implicitly unwrapped optionals exist. It's helpful not to have to write if let all the time because you know they'll have value by the time you need them. Example: } - 隐式解包变量声明:因为变量可能以 nil 开始,但在你需要使用它之前总会有一个值,所以隐式解包可选类型存在。不必一直写 if let 很有用,因为你知道在你需要它们时它们会有值。示例: var v = b! var v = b!
A single unit of code distribution in ios Swift is referred to as a module. The Swift "import" keyword can be used to import a framework or application that has been created and shipped as a single unit. In Swift, each Xcode build target is treated as an independent module. An example of using the "import" keyword is given below:
在 iOS Swift 中,单一代码分发单元被称为模块。Swift 的“import”关键字可用于导入已创建并作为单一单元分发的框架或应用程序。在 Swift 中,每个 Xcode 构建目标都被视为一个独立模块。下面给出使用“import”关键字的示例:
import UIKit
import UIKit
1625. Explain the difference between Self and self in ios Swift.
There is a distinction between Self (capital S) and self (small S) when writing protocols and protocol extensions. When used with a capital S, Self refers to the protocol compliant type, such as String or Int. When used with a lowercase S, self refers to the value contained within that type, such as "hi" or 999, for instance.
Consider the following SquareInteger extension as an example:
以下面的 SquareInteger 扩展为例:
extension SquareInteger {
extension SquareInteger { func squareANumber() -> Self { func squareANumber() -> Self { return self * self return self * self } } Remember that Self with a capital S refers to any type that follows the protocol. Because Int conforms to SquareInteger in the example above, when called on Int, the method returns an Int. Self with a lowercase S, on the other hand, refers to the type's current value. If the preceding example were run on an Int containing the value 4, the result would be 4 * 4. 请记住,大写 S 的 Self 指的是遵循协议的任何类型。因为在上面的例子中 Int 遵循 SquareInteger,当在 Int 上调用时,该方法返回一个 Int。另一方面,小写 s 的 self 指的是类型的当前值。如果前面的例子在一个包含值 4 的 Int 上运行,结果将是 4 * 4。
1626. What do you understand about PLIST in ios? List some examples of types of PLIST.
The abbreviation PLIST in ios stands for Property List. PLIST is a value and key dictionary that can be saved in our file system using the .plist file extension. The property list is used to store a smaller quantity of data in a portable and lightweight manner. In most cases, they are written in XML.
iOS 中的缩写 PLIST 代表属性列表(Property List)。PLIST 是一个键值字典,可以使用 .plist 文件扩展名保存到我们的文件系统中。属性列表用于以可移植且轻量的方式存储少量数据。大多数情况下,它们是用 XML 编写的。
The following are examples of several sorts of property lists: - Binary Property List
以下是一些不同类型的属性列表的例子: - 二进制属性列表
XML Property List
1627. ASCII Legacy Property ListQuestion: What do you understand about training closure syntax in ios Swift?
Many iOS Swift functions accept multiple parameters, the last of which is a closure. Trailing closure syntax is a small amount of syntactic sugar that makes reading and writing common code easier.
许多 iOS Swift 函数接受多个参数,其中最后一个参数是闭包。尾随闭包语法是一小部分语法糖,使得读取和编写常见代码更加容易。
func RunClosureAfterGreeting(name: String, closure: () -> ()) { print("Hi, (name)!!!") print("Hi, (name)!!!") closure() closure() } Instead of the above code snippet, we can write the following code (which is way cleaner than the previous one): 除了上面的代码片段,我们可以编写以下代码(这比之前的代码简洁得多):
RunClosureAfterGreeting(name: "Sonia") {
在问候之后运行闭包(名称:“Sonia”){ print("The closure has been run") 打印(“闭包已执行”) }
A protocol, in its most basic form, explains what an unknown sort of object can accomplish. It has two or three different sorts of properties, as well as procedures. Protocol never includes anything inside the methods, nor does it provide actual storage for the properties. You can build extensions to your protocols that give default implementations of the methods in a more advanced form. However, you are still unable to provide storage for properties.
extension Car : CustomStringConvertible {
扩展 Car : CustomStringConvertible { var description : String { get { return "Car: (colour)" } } 变量描述:字符串 { 获取 { 返回 “Car: (颜色)” } } }
Classes are tangible objects. They are not needed to embrace protocols, which means they do not have to implement the required attributes and methods. Classes can be used to generate objects, whereas protocols are simply typed declarations. Consider protocols to be abstract definitions, whereas classes and structs are actual objects that can be created. An example of a class is given below:
class Car {
class Car { var colour: String 变量颜色:字符串 }
1629. How should one consider the usage of strong, weak and unowned references?
Ask yourself, "Am I dealing with reference types?" to see if you need to worry about strong, weak, or unowned. If you are working with Structs or Enums, ARC is not in charge of memory management, so you do not have to worry about defining weak or unowned constants or variables.
In hierarchical relationships, strong references are acceptable when the parent refers to the child, but not when the child refers to the parent. Strong references are, in fact, the most appropriate type of reference the majority of the time.
If two instances are optionally linked, make sure one of them has a weak reference to the other.
如果两个实例是可选关联的,确保其中一个对另一个持有弱引用。
When two instances are linked to the point where one cannot exist without the other, the instance with the obligatory dependency must keep an unowned reference to the other instance.
If all of the following conditions are met, you should use a set rather than an array: - You only want to add each item once. Duplicates are never permitted in sets.
The order of the items in the collection is irrelevant to you.
You are storing Hashable types, either your own or those provided by Swift, such as strings and integers. Hash values are used in sets to look for things quickly.
1631. Show the use of "self" in a method using an example.
In Swift, the self property of an instance is a special property that holds the instance itself. In most cases, self appears in a class, structure, or enumeration's initializer or method. The most common use of self is in initializers when you are likely to want parameter names that match your type's property names, such as this:
在 Swift 中,实例的 self 属性是一个特殊属性,它持有实例本身。在大多数情况下,self 出现在类、结构体或枚举的初始化器或方法中。self 最常见的用途是在初始化器中,因为此时你可能希望参数名与类型的属性名匹配,例如这样:
struct student {
struct student { var myName: String var myName: String var myFriend: String var myFriend: String init(myName: String, myFriend: String) { init(myName: String, myFriend: String) { print("(name) is being enrolled in class...") print("(name) is being enrolled in class...") self.myName = myName self.myName = myName self.myFriend = myFriend self.myFriend = myFriend } }
1632. How can we use the "inout" parameter in ios Swift? Explain with an example.
By default, function parameters are constants. Changing the value of a function parameter from within the function's body causes a compile-time error. Modifying the local variable also modifies the passed in arguments, which is known as the "inout" parameter. The passed-in arguments will have the same value if it is not present. Trying to remember the reference type while using inout and the value type when not using it. The swap function, which modifies the parameters handed in, is an excellent example. Consider reducing the copying overhead as well. If you have a function that takes a memory-intensive large value type as an argument (say, a huge structure type) and returns the same type, and the function return is only used to replace the caller argument, the inout parameter is the associated function parameter to use. As we can see in the example given below, a call to the function "demoFunction" copies arguments to function property 'aBigStruct'(copy 1) and the function property is mutated after which, the function returns a copy of the mutated property to the caller (copy 2). However, in the function "demoFunctionWithLessCopyOverhead", call by reference is being done and zero value copy overhead is there because of the usage of inout optimization.
struct demoStruct { private var counter: Int = 1 private var counter: Int = 1 // ... a lot of stored properties // ... 许多存储属性 mutating func incrementCounter() { mutating func incrementCounter() { counter += 1 counter += 1 } } /* call to this function copies argument to function property 'aBigStruct'(copy 1) /* 调用此函数会将参数复制到函数属性'aBigStruct'(复制1) function property is mutated 函数属性被修改 function returns a copy of mutated property to caller (copy 2) */ 函数将修改后的属性副本返回给调用方(副本2) */ func demoFunction(var aBigStruct: MyStruct) -> MyStruct { 函数演示函数(变量 aBigStruct: MyStruct)-> MyStruct { aBigStruct.incrementCounter() aBigStruct.incrementCounter() return aBigStruct 返回 aBigStruct } / call by reference -> zero value copy overhead because of the inout optimization / / 按引用调用 -> 由于inout优化,零值副本开销 / func demoFunctionWithLessCopyOverhead(inout aBigStruct: MyStruct) { 函数演示函数减少副本开销(inout aBigStruct: MyStruct){ aBigStruct.incrementCounter() aBigStruct.incrementCounter() } var ex = MyStruct() var ex = MyStruct() ex = demoFunction(ex) // copy, copy: overhead ex = 演示函数(ex) // 副本,副本:开销 demoFunctionWithLessCopyOverhead(&ex) 演示函数减少副本开销(&ex) // call by reference: no memory reallocation // 按引用调用:无需重新分配内存
Swift Programming
1633. Let us take into consideration the following code snippet in ios Swift:
struct 课程{ var toughness: Int = 3 var 难度: Int = 3 } var courseOne = Course() var 课程一 = 课程() var courseTwo = courseOne var courseTwo = courseOne courseTwo.toughness = 4 courseTwo.toughness = 4 What will be the respective values of courseOne.toughness and courseTwo.toughness? If Course was a class instead of a struct, would the values be any different? 那么 courseOne.toughness 和 courseTwo.toughness 各自的取值是多少?如果 Course 是类而不是结构体,这些值会有所不同吗?
The value of courseOne.toughness will be 3 and the value of courseTwo.toughness will be 4 if Course is a structure since Structures in ios Swift are value types and the following line just copies the courseOne to courseTwo by value and not by reference:
var courseTwo = courseOne If Course was a class instead of a struct, then the above given line would copy courseOne to courseTwo by reference and therefore, the values of both courseOne and courseTwo would be 4 by the end of the code snippet as they have the same address. Classes in ios Swift are Reference types therefore both the given courses have the same address. 如果 Course 是类而不是结构体,那么上面给出的那行代码会按引用将 courseOne 复制到 courseTwo,因此,在代码片段结束时,courseOne 和 courseTwo 的值都会是 4,因为它们具有相同的地址。在 iOS Swift 中类是引用类型,所以给定的两个课程具有相同的地址。
1634. In the given code snippet, we have used var to declare viewOne and let to create viewTwo. Will the last line compile?
在给定的代码片段中,我们使用 var 声明了 viewOne,使用 let 创建了 viewTwo。最后一行能编译吗?
import UIKit var viewOne = UIView() var viewOne = UIView() viewOne.alpha = 0.7 viewOne.alpha = 0.7 let viewTwo = UIView() let viewTwo = UIView() viewTwo.alpha = 0.7 // Does this line compile? viewTwo.alpha = 0.7 // 这行能编译吗? The last line will, in fact, compile. viewOne is a variable that we can reassign to a new UIView object. Because we can only assign a value once with let, the following code will not compile: 最后一行实际上是可以编译的。viewOne 是一个变量,我们可以将其重新赋值给一个新的 UIView 对象。因为使用 let 时我们只能赋值一次,所以以下代码将无法编译:
viewTwo = viewOne // Error: viewTwo is immutable
viewTwo = viewOne // 错误:viewTwo 是不可变的 However, because UIView is a reference-based class, we can change the properties of viewTwo — which means the following code will compile: 然而,因为 UIView 是基于引用的类,我们可以更改 viewTwo 的属性——这意味着以下代码可以编译:
let viewTwo = UIView()
let viewTwo = UIView() viewTwo.alpha = 0.7 // Yes, this compiles! viewTwo.alpha = 0.7 // 是的,这可以编译!
1635. Take a look at the code snippet given below. Will the given code fail to compile? If yes, why?
public class TemperatureClass { private(set) var temp: Double = 50.0 private(set) var temp: Double = 50.0 public func changeTemperature(_ temp: Double) { public func changeTemperature(_ temp: Double) { self.temp = temp self.temp = temp } } let temperatureClass = TemperatureClass() let temperatureClass = TemperatureClass() temperatureClass.changeTemperature(72.3) temperatureClass.changeTemperature(72.3) public struct TemperatureStruct { public struct TemperatureStruct { private(set) var temp: Double = 50.0 private(set) var temp: Double = 50.0 public mutating func changeTemperature(_ temp: Double) { public mutating func changeTemperature(_ temp: Double) { self.temp = temp self.temp = temp } } let temperatureStruct = TemperatureStruct () let temperatureStruct = TemperatureStruct () temperatureStruct.changeTemperature(72.3) temperatureStruct.changeTemperature(72.3) Yes, the code given will fail to compile because of the last line of the code. The TemperatureStruct has a mutating method to change its internal variable temp, which is correctly declared. Because we called changeTemperature on an object generated using let, which is immutable, the compiler gives an error. To make the example compile, change let to var. 是的,给定的代码会编译失败,因为代码的最后一行。TemperatureStruct 有一个 mutating 方法来更改其内部变量 temp,该方法声明正确。因为我们对一个使用 let 生成的对象调用了 changeTemperature,该对象是不可变的,编译器会报错。要使示例编译通过,将 let 改为 var。
Methods that affect the internal state of a structure must be marked as mutating, but they cannot be invoked from immutable variables.
影响结构体内部状态的方法必须标记为 mutating,但它们不能从不可变变量中调用。
1636. Predict the output of the following ios Swift program:
var item = "apples" let closure = { [item] in let closure = { [item] in print("He wanted to eat (item)") print("He wanted to eat (item)") } item = "oranges" item = "oranges" closure() closure() The output of the given code snippet will be "He wanted to eat apples". When we define the closure, the capture list generates a duplicate of the item. This means that even if you modify the value of an object, the captured value remains the same. 给定代码片段的输出将是"He wanted to eat apples"。当我们定义闭包时,捕获列表会生成item的一个副本。这意味着即使你修改了对象的值,捕获的值仍然保持不变。
1637. Predict the output of the ios Swift code snippet given below
var item = "apples" let closure = { let closure = { print("He wanted to eat (item)") print("He wanted to eat (item)") } item = "oranges" item = "oranges" closure() closure() The above-given code snippet prints "He wanted to eat oranges". If you do not include a capture list in the closure, the compiler will use a reference rather than a copy. As a result, any change to the variable is reflected when the closure is invoked. 上面给出的代码片段输出"He wanted to eat oranges"。如果你在闭包中没有包含捕获列表,编译器将使用引用而不是副本。因此,当闭包被调用时,对变量的任何更改都会被反映出来。
1638. Take into consideration the following struct:
public struct Temperature{ public var temp: Double public var temp: Double public init(temp: Double) { public init(temp: Double) { self.temp = temp self.temp = temp } } Can we do an initialization using the following code: 我们可以使用以下代码进行初始化吗:
var temp: Temperature = 60.5
var temp: Temperature = 60.5 Yes, Swift specifies protocols that allow you to use the assignment operator to initialize a type with literal values. Literal initialization of a certain type is possible by adopting the corresponding protocol and supplying a public initializer. You implement ExpressibleByFloatLiteral as follows in the example of Temperature: 是的,Swift 指定了协议,允许你使用赋值运算符来用字面量值初始化一个类型。通过采纳相应的协议并提供公共初始化器,可以实现特定类型的字面量初始化。在 Temperature 的例子中,你按照如下方式实现 ExpressibleByFloatLiteral:
extension Temperature: ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { public init(floatLiteral value: FloatLiteralType) { self.init(temp: value) self.init(temp: value) } } After this, we can do the above-given initialization without any errors. 在此之后,我们可以无错误地执行上述给定的初始化。
1639. To conduct arithmetic or logic tasks, Swift offers a collection of predefined operators. It also enables for the construction of bespoke unary and binary operators.
Define and implement a custom power ^^ operator that satisfies the following requirements: - As arguments, it accepts two Ints.
定义并实现一个满足以下要求的自定义幂 ^^ 操作符:- 作为参数,它接受两个 Int。
The first parameter is returned after raising it to the second parameter's power.
The equation is correctly evaluated using the conventional algebraic sequence of operations.
Overflow errors are not taken into account. There are two steps to creating a new custom operator: - Declaration: The "operator" keyword is used in the declaration to indicate the type of the operator (unary or binary), the sequence of letters that make up the operator, associativity, and precedence. The operator here is ^^ and the type is infix (binary) in this case. Equal precedence operators ^^ should evaluate the equation from right to left (associativity is right). The following is the declaration step:
创建新的自定义操作符有两个步骤:- 声明:在声明中使用 "operator" 关键字来指示操作符的类型(一元或二元)、构成操作符的字母序列、结合性和优先级。这里的操作符是 ^^,在这种情况下类型是 infix(二元)。具有相同优先级的操作符 ^^ 应从右到左评估表达式(结合性为右)。以下是声明步骤: precedencegroup ExponentPrecedence { precedencegroup ExponentPrecedence { higherThan: MultiplicationPrecedence higherThan: MultiplicationPrecedence associativity: right associativity: right } infix operator ^^: ExponentPrecedence - Implementation: In Swift, there is no set precedence for exponential operations. Exponents should be calculated before multiplication and division in the normal algebra sequence of operations. As a result, you will need to set custom precedence that puts them ahead of multiplication. The following is the implementation step: infix operator ^^: ExponentPrecedence - 实现:在 Swift 中,对于指数运算没有固定的优先级。在正常的代数运算顺序中,指数应在乘法和除法之前计算。因此,您需要设置自定义优先级,使其置于乘法之前。以下是实现步骤: func ^^(base: Int, exponent: Int) -> Int { func ^^(base: Int, exponent: Int) -> Int { let left = Double(base) let left = Double(base) let right = Double(exponent) let right = Double(exponent) let powerValue = pow(left, right) let powerValue = pow(left, right) return Int(powerValue) return Int(powerValue) }
It can be noted that as the program does not take overflows into consideration, in the event of the operation producing a result that Int can't represent, for example, a value more than Int.max, then a runtime error occurs.
可以注意到,由于程序没有考虑溢出情况,当操作产生的结果无法用 Int 表示时,例如值超过 Int.max,就会发生运行时错误。
1640. You are on a two-dimensional infinite grid where you can move in any of the eight directions (x,y) to (x-1, y-1), (x-1, y), (x-1, y+1), (x , y-1), (x , y+1), (x+1, y-1), (x+1, y) , (x+1, y+1).
You are given a list of points to cover and the order in which you must do so. Write an ios Swift code to give the shortest number of steps you can take to achieve it. You begin from the first point of the given list.
给定一个需要覆盖的点列表以及必须覆盖的顺序。编写一个 ios Swift 代码,给出实现这一目标所需的最少步数。你从给定列表的第一个点开始。
Because the order in which the points are covered is already known, the problem is reduced to figuring out how to calculate the distance between two points (A, B) and the distance between two points (A, B) and the distance between two points (A, B) and the distance between two points (A, B) and the distance between two points (A, B) and the distance (C, D). It is worth noting that just X = abs(A-C) and Y = abs(A-C) are important (B-D). You will progress along the diagonal while X and Y are both positive, and X and Y will both decrease by one. When one of them reaches zero, you move on to the next stage, reducing the remaining number by one. In other words, the total number of steps would be equal to the maximum number of steps (X, Y)
由于覆盖点的顺序已知,问题就简化为如何计算两点 (A, B) 之间的距离以及两点 (C, D) 之间的距离。值得注意的是,只需要 X = abs(A-C) 和 Y = abs(B-D) 这两个值。当 X 和 Y 都为正时,你会沿对角线前进,X 和 Y 都会各减 1。当其中一个变为零时,进入下一阶段,将剩余数量减 1。换句话说,总步数等于 X 和 Y 中的最大值。
The code in ios Swift to solve this given problem is given below:
下面给出了解决这个问题的 ios Swift 代码:
import Foundation
import Foundation class Solution { class Solution { func coverEveryPoint(_ X: inout [Int], _ Y: inout [Int]) -> Int { func coverEveryPoint(_ X: inout [Int], _ Y: inout [Int]) -> Int {
结构体 Cat{ } func showCat(cat: Cat?) { 函数 showCat(cat: Cat?) { guard let c = cat else { guard let c = cat else { print("No presence of cat") 打印("没有猫的存在") } print(c) 打印(c) } The problem with the given code is that a guard's else block requires an escape path, which can be achieved by returning, throwing an exception, or calling a @noreturn . Adding a return statement is the simplest approach: 给定代码的问题在于,guard 的 else 块需要一条退出路径,这可以通过返回、抛出异常或调用 @noreturn 来实现。添加 return 语句是最简单的方法:
func showCat(cat: Cat?) {
函数 showCat(cat: Cat?) { guard let c = Cat else { guard let c = Cat else { print("No presence of cat") 打印("没有猫的存在") return return } print(c) 打印(c) } A fatalError() can also be called which is a @noreturn function: 也可以调用 fatalError(),它是一个 @noreturn 函数:
struct Cat{
结构体 Cat{ } func showCat(cat: Cat?) { 函数 showCat(cat: Cat?) { guard let c = Cat else { guard let c = Cat else { print("No presence of cat") 打印("没有猫的存在") fatalError() fatalError() } print(c) 打印(c) }
1642. This below given difficult code sorts an array of fruits. Write down ways to code the given logic in a simpler way than the code given below.
var fruits = ["apples", "oranges", "papaya", "kiwi"]
var fruits = ["apples", "oranges", "papaya", "kiwi"] fruits.sort { (a: String, b: String) -> Bool in fruits.sort { (a: String, b: String) -> Bool in return a < b return a < b } print(fruits) print(fruits) There are three ways in which we can simplify the given code snippet: 有三种方式可以简化给定的代码片段:
fruits.sort { (a,b) in return a < b }
fruits.sort { (a,b) in return a < b } fruits.sort { $0 < $1 } fruits.sort { $0 < $1 } fruits.sort(by: <) fruits.sort(by: <) Conclusion: 结论: Apple gadgets are used by billions of people all over the world. The number of iOS users has been constantly increasing, which is good news for iOS application developers . iOS Swift developers must also keep up with the latest developments in the iOS Swift community. Make sure you are keeping up with Apple developer news, podcasts, and blogs. This is unlikely to be a question in an interview, but it distinguishes you. We hope that the Swift Interview questions answered here are extremely helpful in studying the fundamentals and advanced topics of iOS Swift. Any beginner or experienced professional who understands these Swift and iOS developer interview questions will be able to pass the interview on the first try. All the best for your upcoming interviews! 苹果的电子产品被全球数十亿人使用。iOS 用户数量持续增长,这对 iOS 应用开发者来说是个好消息。iOS Swift 开发者还必须跟上 iOS Swift 社区的最新发展。确保你跟上苹果开发者新闻、播客和博客。这在面试中不太可能成为问题,但它能让你脱颖而出。我们希望这里解答的 Swift 面试问题在学习 iOS Swift 的基础和高级主题方面极其有帮助。任何理解这些 Swift 和 iOS 开发者面试问题的初学者或有经验的专业人士都能一次通过面试。祝你即将到来的面试一切顺利!
1643. In what ways would you react if a team member made an off-the-wall mistake?
In asking this question, the interviewer is trying to gain an understanding of how you would respond to such an unexpected situation.
在提出这个问题时,面试官试图了解你会如何应对这种意外情况。
Tips: - Demonstrate your analytical skills and ability to solve problems.
提示:- 展示你的分析能力和解决问题的技巧。
Do not put yourself in the position of deciding what to do. Talk about the chain of authority. Sample Answer:
示例回答:
"I recognize that it is not my place to reprimand or discipline my colleagues when they make a mistake on the job. I would try to find out why it happened instead of berating that individual. Upon identifying the problem, I will brainstorm solutions for fixing it and minimizing its impact. As such, if I am not able to rectify the issue, I will report it to higher management to ensure they are addressed appropriately."
Null pointers are one of the most common sources of unexpected runtime errors in programming. TypeScript helps you avoid them to a large degree by enforcing strict null checks.
setting the strictNullChecks property to true in the tsconfig.json configuration file. When the flag is false, TypeScript ignores null and undefined values in the code. When it is true, null and undefined have their distinct types. The compiler throws a type error if you try to use them where a concrete value is expected.
TypeScript doesn’t support static classes, unlike the popular object-oriented programming languages like C# and Java.
TypeScript不支持静态类,这与C#和Java等流行的面向对象编程语言不同。
These languages need static classes because all code, i.e., data and functions, need to be inside a class and cannot exist independently. Static classes provide a way to allow these functions without associating them with any objects.
In TypeScript, you can create any data and functions as simple objects without creating a containing class. Hence TypeScript doesn’t need static classes. A singleton class is just a simple object in TypeScript.
Sometimes, you as a programmer might know more about the type of a variable than TypeScript can infer. Usually, this happens when you know the type of an object is more specific than its current type. In such cases, you can tell the TypeScript compiler not to infer the type of the variable by using type assertions.
TypeScript provides two forms to assert the types. - as syntax:
TypeScript提供了两种断言类型的形式。- as语法: let value: unknown = "Foo"; let value: unknown = "Foo"; let len: number = (value as string).length; - <> syntax: let len: number = (value as string).length; - <>语法: let value: unknown = "Foo"; let value: unknown = "Foo"; let len: number = (value).length; let len: number = (value).length;
Type assertions are similar to typecasting in other programming languages such as C# or Java. However, unlike those languages, there’s no runtime penalty of boxing and unboxing variables to fit the types. Type assertions simply let the TypeScript compiler know the type of the variable.
You can destructure tuple elements by using the assignment operator (=). The destructuring variables get the types of the corresponding tuple elements.
你可以通过使用赋值运算符(=)来解构元组元素。解构变量会获得相应元组元素的类型。
let employeeRecord: [string, number] = ["John Doe", 50000];
let employeeRecord: [string, number] = ["John Doe", 50000]; let [emp_name, emp_salary] = employeeRecord; let [emp_name, emp_salary] = employeeRecord; console.log(Name: ${emp_name}); // "Name: John Doe" console.log(Name: ${emp_name}); // "Name: John Doe" console.log(Salary: ${emp_salary}); // "Salary: 50000" console.log(Salary: ${emp_salary}); // "Salary: 50000" After destructuring, you can’t assign a value of a different type to the destructured variable. For example, 解构之后,你不能将不同类型的值赋给解构后的变量。例如,
emp_name = true; // Type 'boolean' is not assignable to type 'string'.(2322)
Tuples are a special type in TypeScript. They are similar to arrays with a fixed number of elements with a known type. However, the types need not be the same.
// 声明一个元组类型并初始化它 let values: [string, number] = ["Foo", 15]; let values: [string, number] = ["Foo", 15];
// Type 'boolean' is not assignable to type 'string'.(2322)
// 类型“boolean”不可分配给类型“string”。(2322) // Type 'string' is not assignable to type 'number'.(2322) // 类型“string”不可分配给类型“number”。(2322) let wrongValues: [string, number] = [true, "hello"]; // Error let wrongValues: [string, number] = [true, "hello"]; // 错误 Since TypeScript 3.0, a tuple can specify one or more optional types using the ? as shown below. 自 TypeScript 3.0 起,元组可以使用 ? 指定一个或多个可选类型,如下所示。
let values: [string, number, boolean?] = ["Foo", 15];
let values: [string, number, boolean?] = ["Foo", 15];
1649. What are type aliases? How do you create one?
Intersection types let you combine the members of two or more types by using the ‘&’ operator. This allows you to combine existing types to get a single type with all the features you need.
Consider the following example where the variable value belongs to a union type consisting of strings and numbers. The value is initialized to string “Foo”. Because it can only be a string or a number, we can change it to a number later, and the TypeScript compiler doesn’t complain.
考虑以下示例,其中变量 value 属于由字符串和数字组成的联合类型。该值被初始化为字符串 “Foo”。因为它只能是字符串或数字,所以我们可以在稍后将其改为数字,而 TypeScript 编译器不会报错。
let value: string | number = "Foo";
let value: string | number = "Foo"; value = 10; // Okay value = 10; // 没问题 However, if we try to set the value to a type not included in the union types, we get the following error. 但是,如果我们尝试将值设置为联合类型中未包含的类型,就会收到以下错误。
value = true; // Type 'boolean' is not assignable to type 'string | number'.(2322)
value = true; // 类型 'boolean' 不能赋给类型 'string | number'。(2322) Union types allow you to create new types out of existing types. This removes a lot of boilerplate code as you don’t have to create new classes and type hierarchies. 联合类型允许你从现有类型创建新类型。这省去了大量样板代码,因为你无需创建新的类和类型层次结构。
1652. What are anonymous functions? Provide their syntax in TypeScript.
An anonymous function is a function without a name. Anonymous functions are typically used as callback functions, i.e., they are passed around to other functions, only to be invoked by the other function at a later point in time. For example,
Abstract classes are similar to interfaces in that they specify a contract for the objects, and you cannot instantiate them directly. However, unlike interfaces, an abstract class may provide implementation details for one or more of its members.
An abstract class marks one or more of its members as abstract. Any classes that extend an abstract class have to provide an implementation for the abstract members of the superclass.
抽象类将其一个或多个成员标记为抽象。任何继承抽象类的类都必须为父类的抽象成员提供实现。
Here is an example of an abstract class Writer with two member functions. The write() method is marked as abstract, whereas the greet() method has an implementation. Both the FictionWriter and RomanceWriter classes that extend from Writer have to provide their specific implementation for the write method.
abstract class Writer { abstract write(): void; abstract write(): void;
greet(): void {
greet(): void { console.log("Hello, there. I am a writer."); console.log("你好,我是一名作家。"); } }
class FictionWriter extends Writer {
class FictionWriter extends Writer { write(): void { write(): void { console.log("Writing a fiction."); console.log("正在写一部小说。"); } }
class RomanceWriter extends Writer {
class RomanceWriter extends Writer { write(): void { write(): void { console.log("Writing a romance novel."); console.log("正在写一部爱情小说。"); } }
const john = new FictionWriter();
const john = new FictionWriter(); john.greet(); // "Hello, there. I am a writer." john.greet(); // "你好,我是作家。" john.write(); // "Writing a fiction." john.write(); // "正在写小说。"
const mary = new RomanceWriter();
const mary = new RomanceWriter(); mary.greet(); // "Hello, there. I am a writer." mary.greet(); // "你好,我是作家。" mary.write(); // "Writing a romance novel." mary.write(); // "正在写言情小说。"
1654. How to make object properties immutable in TypeScript? (hint: readonly)
You can mark object properties as immutable by using the readonly keyword before the property name. For example:
你可以通过在属性名前使用readonly关键字来将对象属性标记为不可变。例如:
interface Coordinate {
interface Coordinate { readonly x: number; readonly x: number; readonly y: number; readonly y: number; } When you mark a property as readonly, it can only be set when you initialize the object. Once the object is created, you cannot change it. 当你将属性标记为readonly时,它只能在初始化对象时被设置。一旦对象创建完成,你就不能更改它。
let c: Coordinate = { x: 5, y: 15 };
let c: Coordinate = { x: 5, y: 15 }; c.x = 20; // Cannot assign to 'x' because it is a read-only property.(2540) c.x = 20; // 无法分配给'x',因为它是一个只读属性。(2540)
A typical TypeScript project references other third-party TypeScript libraries such as JQuery to perform routine tasks. Having type information for the library code helps you in coding by providing detailed information about the types, method signatures, etc., and provides IntelliSense.
A type declaration file is a text file ending with a .d.ts extension providing a way to declare the existence of some types or values without actually providing implementations for those values. It contains the type declarations but doesn’t have any source code. It doesn’t produce a .js file after compilation.
Triple-slash directives are single-line comments that contain a single XML tag. TypeScript uses this XML tag as a compiler directive.
三斜线指令是包含单个 XML 标签的单行注释。TypeScript 将此 XML 标签用作编译器指令。
You can only place a triple-slash directive at the top of the containing file. Only single or multi-line comments can come before a triple-slash directive. TypeScript treats them as regular comments if it occurs in the middle of a code block, after a statement.
The primary use of triple-slash directives is to include other files in the compilation process. For example, the following directive instructs the compiler to include a file specified by the path in the containing TypeScript file.
/// Triple-slash directives also order the output when using --out or --outFile. The output files are produced to the output file location in the same order as the input files.
The in operator is used to find if a property is in the specified object. It returns true if the property belongs to the object. Otherwise, it returns false.
in 运算符用于查找属性是否在指定对象中。如果属性属于该对象,则返回 true。否则,返回 false。
An implements clause is used to check that a class satisfies the contract specified by an interface. If a class implements an interface and doesn’t implement that interface, the TypeScript compiler issues an error.
class Job implements Runnable { run() { run() { console.log("running the scheduled job!"); console.log("运行定时任务!"); } }
// Class 'Task' incorrectly implements interface 'Runnable'.
// 类'Task'错误地实现了接口'Runnable'。 // Property 'run' is missing in type 'Task' but required in type 'Runnable'.(2420) // 类型'Task'中缺少属性'run',但类型'Runnable'中需要该属性。(2420) class Task implements Runnable { class Task implements Runnable { perform() { perform() { console.log("pong!"); console.log("砰!"); } } A class can implement more than one interface. In this case, the class has to specify all the contracts of those interfaces. 一个类可以实现多个接口。在这种情况下,该类必须满足所有这些接口的所有约定。
In TypeScript, you can refer to specific strings and numbers as types.
在TypeScript中,你可以将特定的字符串和数字作为类型引用。
let foo: "bar" = "bar";
let foo: "bar" = "bar";
// OK
// 正确 foo = "bar"; foo = "bar";
// Error: Type '"baz"' is not assignable to type '"bar"'.(2322)
// 错误:类型'"baz"'不可分配给类型'"bar"'。(2322) foo = "baz"; foo = "baz"; String literal types on their own are not that useful. However, you can combine them into unions. This allows you to specify all the string values that a variable can take, in turn acting like enums. This can be useful for function parameters. 字符串字面量类型本身并不那么有用。然而,你可以将它们组合成联合类型。这允许你指定变量可以取的所有字符串值,从而起到类似于枚举的作用。这可以用于函数参数。
function greet(name: string, greeting: "hi" | "hello" | "hola") {
Template literal types are similar to the string literal types. You can combine them with concrete, literal types to produce a new string literal type. Template literal types allow us to use the string literal types as building blocks to create new string literal types.
// 类型 Shape = "Grid GraphPoint" type Shape = Grid ${Point}; type Shape = Grid ${Point}; Template literal types can also expand into multiple strings via unions. It helps us create the set of every possible string literal that each union member can represent. 模板字面量类型也可以通过联合类型扩展为多个字符串。它帮助我们创建每个联合成员可以表示的每一种可能字符串字面量的集合。
type Color = "green" | "yellow";
type Color = "green" | "yellow"; type Quantity = "five" | "six"; type Quantity = "five" | "six";
Inheritance allows a class to extend another class and reuse and modify the behavior defined in the other class. The class which inherits another class is called the derived class, and the class getting inherited is called the base class.
In TypeScript, a class can only extend one class. TypeScript uses the keyword ‘extends’ to specify the relationship between the base class and the derived classes.
volume() { return "Square doesn't have a volume!" return "Square doesn't have a volume!" } }
const sq = new Square(10);
const sq = new Square(10);
console.log(sq.area()); // 100
console.log(sq.area()); // 100 console.log(sq.volume()); // "Square doesn't have a volume!" console.log(sq.volume()); // "正方形没有体积!" In the above example, because the class Square extends functionality from Rectangle, we can create an instance of square and call both the area() and volume() methods. 在上述示例中,由于Square类从Rectangle扩展了功能,我们可以创建一个正方形实例,并同时调用area()和volume()方法。
1662. What are conditional types? How do you create them?
A conditional type allows you to dynamically select one of two possible types based on a condition. The condition is expressed as a type relationship test.
条件类型允许你根据条件动态选择两种可能类型之一。条件表示为类型关系测试。
C extends B ? TypeX : TypeY
C extends B ? TypeX : TypeY Here, if type C extends B, the value of the above type is TypeX. Otherwise, it is TypeY. 这里,如果类型C扩展了B,上述类型的值就是TypeX。否则,就是TypeY。
function perform(fn: Function) { fn(10); fn(10); } You can always call a value of the Function type, and it returns a value of ‘any’ type. 你总是可以调用Function类型的值,并且它返回‘any’类型的值。
1664. List some of the utility types provided by TypeScript and explain their usage.
TypeScript provides various utility types that make common type transformations easy. These utility types are available globally. Here are some of the essential utility types included in TypeScript.
TypeScript provides three keywords to control the visibility of class members, such as properties or methods. - public: You can access a public member anywhere outside the class. All class members are public by default.
protected: A protected member is visible only to the subclasses of the class containing that member. Outside code that doesn’t extend the container class can’t access a protected member.
private: A private member is only visible inside the class. No outside code can access the private members of a class.
1666. Explain the different variants of the for loop in TypeScript.
Symbols were introduced in ES6 and are supported by TypeScript. Similar to numbers and strings, symbols are primitive types. You can use Symbols to create unique properties for objects.
Symbol 在 ES6 中引入,并由 TypeScript 支持。与数字和字符串类似,symbol 是原始类型。你可以使用 Symbol 为对象创建唯一属性。
You can create symbol values by calling the Symbol() constructor, optionally providing a string key.
你可以通过调用 Symbol() 构造函数来创建符号值,并可选地提供一个字符串键。
let foo = Symbol();
let foo = Symbol(); let bar = Symbol("bar"); // optional string key let bar = Symbol("bar"); // 可选的字符串键 A key characteristic of symbols is that they are unique and immutable. 符号的一个关键特性是它们是唯一且不可变的。
let foo = Symbol("foo");
let foo = Symbol("foo"); let newFoo = Symbol("foo"); let newFoo = Symbol("foo");
let areEqual = foo === newFoo;
let areEqual = foo === newFoo; console.log(areEqual); // false, symbols are unique console.log(areEqual); // false,符号是唯一的
1668. Explain how optional chaining works in TypeScript.
Optional chaining allows you to access properties and call methods on them in a chain-like fashion. You can do this using the ‘?.’ operator.
可选链允许你以链式方式访问属性并在其上调用方法。你可以使用 ‘?.’ 运算符来实现这一点。
TypeScript immediately stops running some expression if it runs into a ‘null’ or ‘undefined’ value and returns ‘undefined’ for the entire expression chain.
Function overloading allows us to define multiple functions with the same name, as long as their number of parameters or the types of parameters are different.
函数重载允许我们定义多个同名函数,只要它们的参数数量或参数类型不同。
The following example defines two overloads for the function buildDate. The first overload takes a number as a parameter, whereas the second takes three numbers as parameters. These are called overload signatures.
The body of the function also called an implementation signature, follows the overload signatures. You can’t call this signature directly, as it’s not visible from the outside. It should be compatible with the overload signatures.
TypeScript can infer the type of a variable when you don’t provide an explicit type. This is known as type inference. This is usually done when the variables or parameters are initialized during the declaration.
When the TypeScript compiler uses the location (or context) of a variable to infer its type, it’s called contextual typing.
当TypeScript编译器使用变量的位置(或上下文)来推断其类型时,这被称为上下文类型推断。
In the following example, TypeScript uses the Window.onmousedown function type information to infer the type of the function expression on the right-hand side of the assignment. This allows it to infer the type of the e parameter, which does have a button property but not a property named foo.
Usually, when we don’t provide any type on a variable, TypeScript assumes ‘any’ type. For example, TypeScript compiles the following code, assuming the parameter ‘ s’ is of any type. It works as long as the caller passes a string.
函数解析(s) { console.log(s.split(' ')); console.log(s.split(' ')); } parse("Hello world"); // ["Hello", "world"] parse("Hello world"); // ["Hello", "world"] However, the code breaks down as soon as we pass a number or other type than a string that doesn’t have a split() method on it. For example, 然而,一旦我们传入数字或其他不具有split()方法的类型(而非字符串),代码就会崩溃。例如,
function parse(s) {
函数解析(s) { console.log(s.split(' ')); // [ERR]: s.split is not a function console.log(s.split(' ')); // [错误]: s.split 不是一个函数 } parse(10); parse(10); noImplicitAny is a compiler option that you set in the tsconfig.json file. It forces the TypeScript compiler to raise an error whenever it infers a variable is of any type. This prevents us from accidentally causing similar errors. noImplicitAny是你在tsconfig.json文件中设置的编译器选项。它强制TypeScript编译器在推断变量为any类型时引发错误。这可以防止我们意外造成类似错误。
Parameter 's' implicitly has an 'any' type.(7006)
参数“s”隐式具有“any”类型。(7006) function parse(s) { 函数解析(s) { console.log(s.split(' ')); // [ERR]: s.split is not a function console.log(s.split(' ')); // [错误]: s.split 不是一个函数 }
1673. What is the difference between mounted and created hooks in Vue.js?
Throughout their lifecycle, components experience numerous stages, where both created and mounted hooks function as tools to execute relevant actions. Although there is some difference between them. Those are -
在组件的整个生命周期中,它们经历多个阶段,其中 created 和 mounted 钩子都是执行相关操作的工具。虽然它们之间有一些区别。那些是 -
When a component is made, the "created" hook is instantly called and provides access to the component's data for tweaking. This hook can be utilized for organizational tasks such as configuring methods, data, and events that are necessary for the overall functionality of the component
As soon as the component's template has been compiled, rendered, and inserted into the Document Object Model (DOM), the "Mounted" hook comes into action. This hook is essential for executing any tasks that require the usage of DOM. This could involve setting up event listeners or kickstarting third-party libraries.
一旦组件的模板被编译、渲染并插入到文档对象模型(DOM)中,"Mounted" 钩子就开始发挥作用。该钩子对于执行任何需要使用 DOM 的任务至关重要。这可能包括设置事件监听器或启动第三方库。
Conclusion
结论 Vue.js is a popular JavaScript framework that is widely used for building complex, dynamic web applications. Whether you are a seasoned developer or just starting with Vue.js, it's essential to be well-prepared for a Vue.js job interview. This article covered some common Vue.js interview questions that you may encounter, including questions about Vue.js fundamentals, component architecture, routing, state management, and error handling. By studying and practising these questions, you can increase your chances of success and impress your interviewers with your Vue.js knowledge and skills. Remember to keep learning and staying up-to-date with the latest Vue.js features and best practices to become a proficient Vue.js developer. Certainly, here are some tips and tricks that you can follow for answering Vue.js interview questions. Vue.js 是一个流行的 JavaScript 框架,广泛用于构建复杂、动态的 Web 应用程序。无论你是一位经验丰富的开发者还是刚刚开始接触 Vue.js,为 Vue.js 面试做好充分准备是必不可少的。本文涵盖了一些你可能遇到的常见 Vue.js 面试问题,包括关于 Vue.js 基础、组件架构、路由、状态管理和错误处理的问题。通过学习和练习这些问题,你可以增加成功的机会,并用你的 Vue.js 知识和技能给面试官留下深刻印象。记得继续学习并跟上最新的 Vue.js 功能和最佳实践,以成为一名熟练的 Vue.js 开发者。当然,这里有一些你可以遵循的提示和技巧来回答 Vue.js 面试问题。
1674. What is a watcher in Vue.js? When would you use one?
In Vue.js, a watcher is a special object that allows us to watch for changes in a specific data property, and perform some action when that property changes. Watchers are a key part of Vue.js's reactivity system, which automatically triggers the event and updates the view when data changes.
Watchers are particularly useful when we need to perform some action in response to changes in data that cannot be accomplished with computed properties or methods.
当我们需要对数据变化做出响应,而这些变化无法通过计算属性或方法实现时,Watcher 特别有用。
For example, We might use a watcher to update a chart or graph in response to changes in a data source. Or maybe to trigger an API call when a specific data property changes.
例如,我们可能会使用 watcher 来根据数据源的变化更新图表或图形。或者,当特定数据属性发生变化时,触发 API 调用。
1675. How would you handle authentication and authorization in a Vue.js application?
Authentication and authorization are critical aspects of web application development, and Vue.js provides several approaches to handle them. Some commonly used methods are: - Authentication: To handle authentication in a Vue.js application, we can use an authentication library like JWT or OAuth2.0. Once the user logs in, the authentication library will generate a token that you can store in the browser's local storage or cookies. We can then include this token in all subsequent requests to the server to verify the user's identity.
身份验证和授权是 Web 应用程序开发的关键方面,Vue.js 提供了几种处理它们的方法。一些常用的方法包括:- 身份验证:为了处理 Vue.js 应用程序中的身份验证,我们可以使用像 JWT 或 OAuth2.0 这样的身份验证库。一旦用户登录,身份验证库将生成一个令牌,你可以将其存储在浏览器的本地存储或 cookies 中。然后,我们可以在所有后续请求中包含此令牌,以验证用户的身份。 For example - we can use the vue-authenticate library to implement OAuth2.0 authentication in the Vue.js application. Once the user logs in using their credentials, the library will retrieve an access token that we can use to authenticate subsequent requests. - Authorization: To handle authorization in a Vue.js application, we can implement role-based access control (RBAC) or attribute-based access control (ABAC). With RBAC, we can define the roles that correspond to different levels of access, and we assign these roles to users. With ABAC, we can define policies that specify which users are authorized to perform specific actions. 例如 - 我们可以使用 vue-authenticate 库在 Vue.js 应用程序中实现 OAuth2.0 身份验证。一旦用户使用其凭据登录,该库将检索一个访问令牌,我们可以使用它来验证后续请求。- 授权:为了处理 Vue.js 应用程序中的授权,我们可以实现基于角色的访问控制(RBAC)或基于属性的访问控制(ABAC)。使用 RBAC,我们可以定义对应于不同访问级别的角色,并将这些角色分配给用户。使用 ABAC,我们可以定义策略,指定哪些用户被授权执行特定操作。 For example - we can use the vue-acl library to implement RBAC in the Vue.js application. This library provides a middleware that we can use to restrict access to specific routes or components based on the user's role. 例如 - 我们可以使用 vue-acl 库在 Vue.js 应用程序中实现 RBAC。该库提供了一个中间件,我们可以使用它根据用户的角色限制对特定路由或组件的访问。
1676. How do you handle errors in Vue.js? Explain with an example.
There are several ways to handle errors in vue.js depending on the context and the type of error. Here are some common approaches: - Error Handling in Components:
根据上下文和错误类型的不同,在 vue.js 中有几种处理错误的方法。以下是一些常见的方式:- 组件中的错误处理: To handle errors in Vue components, we can use the try-catch block . If an error occurs in the component, it will be caught by the catch block, and you can take appropriate action to handle the error. 要在 Vue 组件中处理错误,我们可以使用 try-catch 块。如果组件中发生错误,它将被 catch 块捕获,你可以采取适当的措施来处理该错误。
For example , you can display an error message to the user, log the error, or even send it to a server for further analysis. Consider the below example code.
To handle errors globally, we can use the errorHandler property of the Vue configuration object. This allows us to catch and handle errors that occur anywhere in your application. Consider the below example code to understand better.
若要全局处理错误,我们可以使用 Vue 配置对象的 errorHandler 属性。这使我们能够捕获并处理应用中任何地方发生的错误。请参考以下示例代码以更好地理解。 import Vue from 'vue' import Vue from 'vue' Vue.config.errorHandler = function (error, vm, info) { Vue.config.errorHandler = function (error, vm, info) { // Handle the error // 处理错误 }
Error Handling in Promises:
For using the Promises in the Vue.js application, we can use the catch method to handle errors that occur during asynchronous operations. Consider the below example code that demonstrates how we can use it.
It uses typescript, a superset of JavaScript that adds features like static typing.
Template
It uses HTML-Based templates.
It uses JSX. JSX allows writing HTML Codes inside javascript.
It also uses HTML-Based templates.
Size
It is a small and compact framework. Size is less than 30KB.
It is also a small and compact framework. Size is less than 30KB.
Angular is a larger framework, with a size of more than 500 KB.
Rendering
Vue.js is primarily a client-side rendering framework, which means it renders the entire application on the client side using JavaScript. Vue.js can also be used for server-side rendering.
React is also primarily a client-side rendering framework, which means it renders the entire application on the client side using JavaScript.
Angular, on the other hand, is designed for both client-side and server-side rendering. It uses a special syntax called Angular Universal to allow you to render your application on the server-side
State
Vue.js has an official state management library called Vuex, which provides a way to manage the state in a centralized and predictable manner.
React, on the other hand, has an unofficial state management library called Redux, which has become very popular in React community. React also has a built-in (useState) hook which can be used for state management.
Angular has built-in state management capabilities and uses a combination of services, observables, and the RxJS library to manage the state.
1678. How would you implement lazy-loading in a Vue.js application?
Lazy loading is basically dividing the code. We can do this cool trick with Webpack, which is just a fancy way of bundling stuff for Vue CLI projects. Here are the general steps to implement lazy-loading in a Vue.js application: - Configure webpack: In the vue.config.js file of your project, you need to set up webpack so that it chops your app into smaller sections by utilizing splitChunks or dynamicImport.
Define a route-based chunk: In the Vue router, we can define some piece of code for a specific route by using the component property and a function. This will return an import statement dynamically for the component.
Use the lazy-loaded component: In your Vue templates, use the component element and bind the attribute to the lazy-loaded component name. Consider the below example for the implementation of this -
考虑以下示例来实现这一点——
>
>
>
1679. How would you integrate a third-party library into a Vue.js application?
To integrate a third-party library into a Vue.js application, we can follow the general steps:
要将第三方库集成到 Vue.js 应用程序中,我们可以遵循以下一般步骤:
Install the library: We can use a package manager like npm or yarn to install the library as a dependency. 2. Import the library: Import the library in the Vue.js application's entry point (e.g., main.js) using the appropriate syntax for the library. This may involve importing the library as a module, loading a script file from a CDN, or using a special plugin for the library. 3. Use the library in your components: Depending on the library, we may need to configure it or initialize it before we can start using it in our Vue.js components. Then, we can use the library's APIs and functions in component methods, computed properties, or lifecycle hooks.
Vuex is a state management pattern and library for Vue.js applications. It provides a centralized store to manage the state of the application and allows synchronization of data between components and predictably manages complex stateful logic.
Here are some common use cases for using Vuex in a Vue.js application: - Large Applications: Vuex can be useful in large applications with many components that need to share data or communicate with each other. By centralizing the state management in a Vuex store, we can avoid passing props and events between components and simplify the code.
Complex State Management: Vuex can help manage complex stateful logic by providing a clear separation of concerns between the state management code and the view components. This can help improve the maintainability and readability of the code.
Debugging: Vuex provides a centralized store that makes it easier to debug the state of the application. By using the Vuex DevTools, we can easily monitor the state changes and debug issues related to state management.
Time Travel: Vuex supports time travel debugging, which allows us to step forward and backwards through the state changes of the application. This can be useful for debugging complex stateful logic or reproducing issues in the application.
Server-Side Rendering: Vuex can be used in conjunction with server-side rendering to provide a consistent state between the client and server. This can help improve the performance and SEO of the application.
1683. How would you optimize the performance of a large Vue.js application?
Optimizing the performance of a large Vue.js application requires several solutions that address different areas of the application. Although adopting specific optimization procedures, combining techniques has proven to deliver the highest return. Consider the following strategies: - - Lazy Loading: Instead of loading everything at once, we can divide the application into smaller chunks and load them on demand using lazy loading. This split-up approach can significantly reduce initial load time and enhance overall application performance.
Code Splitting: We can split the code into smaller chunks. And can load only the required component. Using this we can reduce the size of the application and can improve its performance.
Minification and Compression: We can squeeze the app size and use the minified version of Javascript and CSS files (like jquery.min-js). This speeds up downloads and boosts performance.
Caching: We can cache stuff like pics, fonts, and API responses so we don't put the load on the network as much and make our app run faster.
Use Vuex for State Management: Vue.js provides Vuex (a state management library). This allows management of the state of the application in a centralized store. Using Vuex, we can cut down the number of API calls and make our Vue.js application faster.
Use Async Components: Async components allows to load of components on demand. So using this we can reduce the unnecessary calls/request of components at the initial time.
Optimize Vue.js Directives: We can use v-if instead of v-show for conditionally rendering elements. Also, we can use v-for with the key attribute, and use v-cloak to hide uncompiled Vue.js templates.
Server-Side Rendering: Using Server-Side-Rendering, we can preload some of the necessary HTML, CSS, and JavaScript files. This can improve performance in terms of SEO.
Use Performance Analysis Tools: There are various performance analysis tools that we can use like - Google Chrome Developer tools, Vue.js Developer tools, etc. This helps in debugging the complexity so that we can reduce it and optimize the performance.
1684. What is server-side rendering in Vue.js and how is it different from client-side rendering?
Server-side rendering (SSR) is a web dev trick that involves generating HTML content on the server and shipping it off to the client as a fully-formed HTML page. Vue.js backs up SSR and can be used along with client-side rendering to whip up all-purpose apps. - In the rendering on the client side, the browser snags the basic webpage codes and designs and kicks off the page view on the user side. And when the user fiddles with the page, the side handled by the user reaches out to get fresh data from the server and tweaks the core HTML tags as per the requirements. Going this way has advantages - like cracking open the page in a dash, making some great interactive changes, and making the job of coders a whole lot easier. Yet, it also has disadvantages - like when it comes to SEO, there are going to be some issues, and the page's time-to-content is going to drag a bit.
服务器端渲染(SSR)是一种网络开发技巧,涉及在服务器上生成 HTML 内容,并将其作为完整成形的 HTML 页面发送给客户端。Vue.js 支持 SSR,并且可以与客户端渲染结合使用,以创建多用途应用。 - 在客户端渲染中,浏览器获取基本网页代码和设计,并在用户端启动页面视图。当用户与页面交互时,用户端会向服务器请求新数据,并根据要求调整核心 HTML 标签。这种方式有优点——比如快速打开页面、实现出色的交互性变化,以及让编码工作更加容易。然而,它也有缺点——比如在 SEO 方面会有一些问题,并且页面达到可交互内容的时间会有所拖延。
On the other side, SSR does the HTML content baking on the server end and sends it out to the client as a full HTML page. It takes more time for the page to first show up, but once it does, it's already functioning perfectly. Besides that, SSR has some advantages over-client-side renderings like better search engine optimization, quicker content loading time, and more stable performance on weak devices. To view SSR in Vue.js, we have to use Node. js-based server to spit out the first HTML content. When a user asks for a page, the code on the server side creates the HTML content using Vue.js goodies and sends it to the player. Once the page is ready, the client-side code takes the snippets and updates the DOM as needed. This provides a seamless user experience.
要在 Vue.js 中查看 SSR,我们必须使用基于 Node.js 的服务器来生成初始 HTML 内容。当用户请求页面时,服务器端的代码使用 Vue.js 的功能创建 HTML 内容并将其发送给用户。页面准备好后,客户端代码获取片段并根据需要更新 DOM。这提供了无缝的用户体验。
1685. Explain Directives. Also, explain the purpose of directives in vue.js.
Directives are special attributes that can be applied to DOM elements. The 'v-' prefix easily distinguishes these utilitarian properties and allows elements to demonstrate reactive and declarative behaviour ascribed to them.
指令是可以应用于 DOM 元素的特殊属性。'v-' 前缀使其易于区分为实用属性,并允许元素表现出归因于它们的响应式和声明式行为。
Vue.js directives are used to apply common DOM transformations and data bindings declaratively, removing the need for specialized JavaScript code. They make it simple to apply behaviour to DOM components, improving code readability, understanding, and maintainability. Directive customization and extension can provide give additional functionality.
Vue.js 指令用于声明式地应用常见的 DOM 变换和数据绑定,从而无需专门的 JavaScript 代码。它们使得向 DOM 组件应用行为变得简单,提高了代码的可读性、可理解性和可维护性。指令的定制和扩展可以提供额外的功能。
Some common directives in Vue.js include: - ‘v-if and v-show’: It is used for conditionally rendering the elements based on a Boolean expression.
VueJS has several lifecycle methods that allow developers to handle certain events that occur during the lifecycle of a Vue component. The lifecycle methods of VueJS can be divided into three categories:
Creation: These methods are called when components are created for the first time.
创建:这些方法在组件首次被创建时调用。
beforeCreate(): This method is called before a component is created, and data has not yet been made reactive.
beforeCreate():此方法在组件被创建之前调用,此时数据尚未变为响应式。
created(): This method is called after a component has been created, and data has been made reactive. 2. Mounting: Before a component gets inserted into the DOM, various mounting methods come into play.
created():此方法在组件被创建之后调用,此时数据已变为响应式。 2. 挂载:在组件被插入到 DOM 中之前,各种挂载方法开始发挥作用。
beforeMount(): Prior to the component's mounting to the DOM, the beforeMount() method is invoked
beforeMount():在组件挂载到 DOM 之前,会调用 beforeMount() 方法。
mounted(): method is triggered post-component mounting to the DOM. 3. Updating: Upon the modification of a component's reactive data, the aforementioned approaches get invoked.
beforeUpdate(): Prior to the update of a component's reactive data, this method is invoked.
beforeUpdate():在组件的响应式数据更新之前,此方法会被调用。
updated(): Once the reactive data of a component has been updated, this method is invoked.
updated():当组件的响应式数据更新完成后,此方法会被调用。
Two additional lifecycle methods are called when a component is destroyed: - beforeDestroy(): When the components are about to destroy, this method is called.
You can start by providing a brief introduction to Vue.js and its core features and how it’s relevant to your project. This will help the interviewer understand the context of your project. Other than that, consider some below points that you should keep in mind while answering - - Keep it simple: Avoid getting into unnecessary details and keep your explanation simple and easy to understand.
Understand the basics: Make sure you have a good understanding of the fundamental concepts of Vue.js such as components, directives, and data binding.
Know your project structure: Be familiar with the structure of your project, including the file structure and any relevant dependencies.
Explain the functionality: Clearly explain the main functionality of your project and how it works.
Show your code: Share snippets of your code to demonstrate your understanding and showcase your coding skills.
Demonstrate testing: If applicable, demonstrate any testing methods you used to ensure the functionality of your project.
Discuss scalability: Explain how your project can scale to meet future demands and any techniques you used to ensure scalability.
Emphasize your contribution: Highlight your specific contribution to the project and any challenges you overcame during the development process. Remember to keep your answers brief and to the point, focusing on the most important aspects of your project.
Vue.js can be used to build complex single-page applications, dynamic user interfaces, and reusable components. It can also be used for server-side rendering, mobile app development, and desktop app development. In general, Vue.js is a versatile and flexible framework that can be used for a wide range of web development projects.
Yes, We can conclude that Vue.js has a bright future due to its simplicity, flexibility, and performance. Its reactivity system makes it easy to build complex user interfaces with minimal code. Additionally, its growing community and constant updates ensure it will remain a popular choice for front-end development.
The average salary for a Vue.js developer in India is around ₹600,000 per year, according to Glassdoor. However, salaries can range from around ₹350,000 to over ₹1,500,000 per year, depending on factors such as the developer's experience level, location, company size, and industry.
Vue js is a front-end javascript library used for creating a lightweight single-page web application. It can communicate with APIs and provides a rich user experience.
Vue.js is good for building user interfaces and complex single-page applications with ease. Thanks to its easy-to-learn syntax, reactivity system, and component-based architecture. It is also lightweight, fast, and flexible, making it an excellent choice for developers who want to create responsive and interactive applications.
Certainly, there are some tips and tricks that you can follow for answering Vue.js interview questions: - Before the interview, you can take some time to review the Vue.js documentation. This helps you in understanding the key concepts and features of the framework.
Be familiar with the lifecycle hooks of Vue.js. (Mostly Asked in Interviews). When lifecycle hooks are called. This will help you better understand how components are created and updated.
Make sure that you are very comfortable with creating components and using directives such as v-bind and v-on to manipulate them. (Interviewer might ask to create).
Vue.js templates are a powerful tool for building dynamic user interfaces. Make sure you understand how they work and how to use them effectively. Also, how you have utilized it in your projects.
If you are applying for a role that requires Vuex knowledge, make sure you are familiar with how to use Vuex for state management.
You should be able to debug Vue.js applications using the Vue.js devtools, as well as the browser's console and debugger.
Vue.js is constantly evolving, so make sure you keep up to date with the latest changes and updates.
When answering interview questions, it's important to explain your thought process and the reasoning behind your answers. This will help the interviewer understand how you approach problems and make decisions.
Practice, practice, practice. The best way to prepare for a Vue.js interview is to practice answering sample interview questions. You can find sample questions in this article or you can create your own based on the job description.
Be very confident and enthusiastic about your Vue.js skills and experience. Show the interviewer that you are passionate about the framework and excited about the opportunity to work with it. (This makes the interviewer think that you are the right fit).
UX case studies are an essential component of a stellar UX portfolio. Yet, writing UX case studies can often feel daunting. Developing an effective UX case study entails telling the story of a project and communicating not only what you accomplished but also the reasons for it. The following is an outline of what to include in an UX case study: - Overview: A short description of the company and project.
Problem Statement: State your objectives, such as why you worked on this project and what its objectives were.
Client and Audience: Describe the intended niche for the product or service. This may include what were your target audiences when creating your product or service and who precisely was it designed for.
Roles and Responsibilities: Provide information about your team, including how your responsibilities were shared. Was your team headed by you, or did you have several experts on hand?
Scope and Constraints: Include details regarding your working conditions and your limitations. It may involve tight deadlines, a low budget, or a time zone difference.
Work Process: This stage is crucial to your UX story. It should outline in detail the steps you took as well as why you did it (e.g., to solve user pain points or to increase conversion).
Results and conclusions: You have come to the end of your tale. Describe the results of your efforts, your achievements, the lessons you learned, and the experience you gained.
1695. State difference between HTML elements and HTML tags
HTML elements and HTML tags differ in the following ways:
HTML 元素与 HTML 标签在以下方面有所不同:
HTML Tags HTML 标签
HTML Elements HTML 元素
Tags indicate the start and end of an HTML element, i.e., the container that holds other HTML elements (except ). 标签表示 HTML 元素的开始和结束,即包含其他 HTML 元素的容器(除 外)。
All HTML elements must be enclosed between the start tag and closing tag. 所有 HTML 元素都必须包含在开始标签和结束标签之间。
Each tag begins with a '' symbol. 每个标签都以 '' 符号开头。
The basic structure of an HTML element consists of the start tag (), the close tag () and the content inserted between these tags. HTML 元素的基本结构包括开始标签()、结束标签()以及这两个标签之间插入的内容。
Any text inside ‘’ is called a tag. ‘’ 内的任何文本都称为标签。
A HTML element is anything written in between HTML tags. HTML 元素是写在 HTML 标签之间的任何内容。
jQuery simplifies the process of implementing JavaScript on a website. With jQuery, most common tasks that require a lot of JavaScript code are wrapped into methods that can be invoked with just one line of code. Additionally, jQuery simplifies several complex aspects of JavaScript, such as DOM manipulation and AJAX calls. JQuery is a lightweight JavaScript library that strives to do more with less coding. Following are some features of the jQuery library: - HTML/DOM manipulation
visibility: visible| collapse | hidden | inherit | initial; Property Values: - visible: It specifies that an element must be visible. This is the default value. 属性值:- visible:指定元素必须可见。这是默认值。
hidden: Indicates that the element is not visible, but it does affect the layout.
collapse: Hides an element when it appears on a row or cell in a table.
initial: The visibility property of the element is set to its default value.
inherit: The property has been inherited from its parent.
Display property The Display property specifies how components (such as hyperlinks, divs, headings, etc.) will be displayed on the web page.
Display 属性指定组件(如超链接、div、标题等)在网页上的显示方式。
Syntax:
语法:
display: none | block | inline | inline-block;
display: none | block | inline | inline-block; Property Values: - none: No elements will be displayed. 属性值:- none:不显示任何元素。
inline: This makes the element render or appear as an inline element. This is the default value.
block: This makes the element render or appear as a block-level element.
inline-block: The element is rendered as a block box within an inline box.
CSS, or Cascading Style Sheets, is a style sheet language. Essentially, it controls and oversees how elements should be portrayed on screen, on paper, in speech, or in any other media. CSS allows you to control the text color, font style, spacing between paragraphs, and columns' size and arrangement. This allows you to quickly change the appearance of several web pages at once.
In cases where an image consists of certain words, it is recommended that the image be saved as a GIF instead of a JPG. JPG files have a file compression feature that causes the fonts to become unreadable.
Different image compression formats use different compression techniques for different purposes. - JPEG: The JPEG compression process reduces the size of an image by identifying similar colored areas; the higher the compression level, the more aggressively the process searches for these areas, which can lead to loss of visual information and artifacts at the edges of the compressed region. Colorful photos, illustrations, gradients, and other richly colored images benefit from this compression. It is particularly screenshots, flat icons, simple UI elements, and schematics.
PNG: The PNG compression method reduces the number of colors in the image. It may result in a slight loss of color shades depending on the compression level. PNGs are excellent for UI elements, icons, signs, logos, illustrations that contain text, and screenshots. Unlike JPEGs, they also support transparent areas. In general, PNG files are bigger than JPEG files and do not offer good compression for photos and complex, colored images and gradients.
The Dreamweaver templates typically come with premade CSS templates. All the pages and content on your website can be created, modified, and updated instantly with Dreamweaver templates. By making a site more flexible and consistent, it can increase your productivity. Designers can revise the Dreamweaver template files at once to make changes to the site at their convenience. With the help of a good web designer, you can create a Dreamweaver template out of any HTML or PHP page. You can, however, use readymade templates if you want a consistent design across all pages of your website, but do not know how to create DWT.
The CSS float property can be used to determine how content is positioned and formatted on the page. One of the most common uses of this property is wrapping text around images. A float property can be used to wrap any inline element around a defined HTML element, for example, a paragraph, list, span, div, table, and an iframe. The float property indicates whether an element should float right, left, or not at all.
CSS float 属性可用于确定内容在页面上的定位和格式化方式。该属性最常见的用途之一是让文本围绕图像进行换行。float 属性可用于将任何内联元素围绕定义的 HTML 元素进行环绕,例如段落、列表、span、div、表格和 iframe。float 属性指示元素是否应向右浮动、向左浮动或完全不浮动。
Syntax:
语法:
element {
element { float: value; float: value; } Example1: Float an image in CSS 示例1:在 CSS 中浮动图像
img {
img { float: left; float: left; height: 120px; height: 120px; } Example2: Float other HTML element in CSS 示例2:在 CSS 中浮动其他 HTML 元素
It is possible that you will receive some constructive feedback from clients regarding your designs and may need to adjust them based on updated specifications. Employers typically ask this question to understand how you deal with problems, respond to feedback, and build relationships with clients.
“I encountered this situation while working for a client in the financial sector. The company felt that my design was too sophisticated for many of their customers and might turn away some of their loyal members. I explained to the bank why my web design might be a good fit for the youngest of customers, but ultimately we agreed to a compromise. The final website had a sleek appearance with flashy elements that would appeal to the young audience.”
By asking this question, the interviewer may be trying to ascertain how you work, how well you serve your clients, and how easy it is to work with you. Before answering, take a moment to collect your thoughts so the hiring manager will be able to understand your approach fully.
“First, I always meet with my clients to discuss their needs. Next, I draft a preliminary design and send it to them for review. As the design progresses, I send them regular updates. The completed product is sent to them for review once it has been completed. Whenever updates are required, we talk about what I need to alter, the time frame, and other details.”
As a web designer, it is your responsibility to ensure that your website is positioned well for SEO (Search Engine Optimization) and is responsive so that it can be used effectively by users. Using this interview question, a company can ascertain the designer's familiarity with SEO and responsiveness practices. To demonstrate your knowledge of website optimization, discuss elements such as URL structure, keywords, page titles, meta descriptions, alt text, and H1 tags.
In some cases, fonts work together nicely and make a good combination when displayed together. As a general rule, two fonts are compatible if they are either quite similar, but with at least one significant difference (analogous fonts), or if they are very different, but have one notable characteristic in common (complimentary fonts). - The best way to combine two fonts is to look for their common and unique features (serifs, x-height, historic backgrounds, aperture, thickness, stroke contrast).
Fonts that look too similar should not be combined (e.g., Helvetica and Lucida Grande or Arial and Verdana).
Avoid combining many font styles at once. Stick to two or three font sizes maximum; it will save you time and avoid readers skipping over the content.
Try one serif font and one sans serif font. Especially at contrasting sizes, they tend to work well together.
Choosing contrasting fonts is a good idea. Many ways can be used to create contrast, including weight, size, spacing, color, etc.
It is best to use a single font family. A superfamily contains many styles, weights, and cases within the same typeface. Sticking to one superfamily allows you to create a minimalist layout and have enough variation for your needs.
1710. When deciding on a color scheme, what factors should you take into consideration?
Color schemes are an important part of the design process. Choosing colors for your project isn't easy, but keeping a few things in mind is a good way to ensure that you come up with a great color combination. - Be familiar with the brand identity and what the company does. Get to know what they do, what services or products they offer, what their principles are, and so on. Knowing this will help you determine the right color scheme for their brand.
Get to know the Big Boss better. Simply take a look at what they already use and have been using. See the uniforms, the logos, etc. You should choose a color(s) that reflect the nature of the company and its employees.
Choose colors that are appealing to your target audience. When designing, always keep in mind who you're designing for and what the ultimate objective is. You might need to conduct some research on your target audience, or test different color combinations.
The client/company's emotional relationship with their target market needs to be reflected. Brighter colors are appropriate for brands with high energy, whereas muted colors are appropriate for mature brands.
Pick colors that are associated with positivism to make a lasting impression on the audience. Learn the significance of color in the specific industry.
1711. Are there any ways to reduce the loading time for a page?
The speed and functionality of your website affect not only your users but also your search engine rankings. Here are a few tips for improving your web page loading time. - Decide on a hosting solution that is performance-optimized.
HTML5 introduces many new element types (semantic elements) that may be utilized for marking up complex content. These elements make it easier for machines (such as parsers, search engines, screen readers, etc.) to sift through web pages and understand their content structure. - : A piece of separate content that can exist outside the context of its webpage and has its own heading. This can be used in a news article, blog, product description, etc.
: This is what constitutes the body of a document or an application.
: It is a reference to the main content on the webpage but is not part of that actual content. An example would be the list of related articles relating to the main article.
: It represents navigational or introductory aids that help you navigate through the terrain.
1713. Can comments be inserted into HTML code without being picked up by the browser?
can be used to add comments to HTML code without the browser picking up on it. HTML comments begin with ‘’. Any person viewing the page source code will be able to see HTML comments. Browsers will not render these comments
<!- 这是一个 HTML 注释 -> Conclusion 结论 In a tech interview, you are expected to demonstrate both your technical and communication abilities. As the format and questions of a job interview vary depending on the position and the company, you can expect to be asked a combination of behavioral, technical, and personal questions. An interview for a web design position is nothing to be apprehensive about, especially if you have practiced the most likely questions ahead of time. Your proficiency with web design tools, standards, and best practices will be assessed through knowledge-based questions. Preparation increases your chances of impressing the hiring manager and moving on to the next step. That's why we have compiled a comprehensive list of frequently asked questions during interviews for web designers. 在技术面试中,你不仅要展示技术能力,还要体现沟通能力。由于职位和公司的不同,面试形式和问题也会有所差异,因此你可能会遇到行为、技术和个人方面的问题组合。网页设计职位的面试无需过分担忧,尤其是如果你提前练习了最可能被问到的问题。你的网页设计工具、标准和最佳实践熟练度将通过知识性问题进行评估。充分准备能增加你给招聘经理留下深刻印象并进入下一轮的机会。因此,我们整理了一份全面的网页设计师面试常见问题清单。
In this article, we have provided an overview of web design as well as a list of the top 35+ web designer interview questions that can be helpful to job applicants starting their careers or moving up the career ladder. An ideal candidate should have a deep understanding of key concepts, as well as the ability to articulate their ideas clearly and persuasively. Also, you can enroll in an online course in web design to keep up to date on the latest developments in the industry.
CDN stands for Content Delivery Network. CDNs are geographically distributed groups of servers that deliver Internet content quickly. To provide end-users with fast, secure media delivery and web content, the servers are dispersed across many physical and network locations. Using CDNs can significantly reduce load times since they deliver files at higher bandwidth from servers located closer to your visitors than your own web server.
For faster access and better performance, web programmers and developers can leverage CDNs to host their jQuery Libraries . Microsoft and Google have already put jQuery on their CDNs, so developers don't have to worry about that. Their only task now is to reference the hosted jQuery library.
W3C stands for World Wide Web Consortium. Founded in 1994, W3C is an international organization devoted to the improvement of the web. The W3C strives to help the web reach its full potential and ensure its continuous development. It sets standards (protocols) for the WWW (World Wide Web) to allow for interoperability and cooperation between all stakeholders. It develops various protocols or standards as a means of growing the web.
CSS selectors are used by web designers to specify or select HTML elements they want to style. Following are a few of the most commonly used CSS selectors:
CSS 选择器由网页设计师用来指定或选择他们想要进行样式设置的 HTML 元素。以下是几个最常用的 CSS 选择器:
ID Selector: It selects HTML elements using specific id attributes.
Syntax: #idname
语法:#idname Example: Here is the CSS rule that will be applied to the HTML element having id="para1". 示例:以下是应用于具有 id="para1" 的 HTML 元素的 CSS 规则。
para1 {
text-align: left;
text-align: left; color: blue; color: blue; }
Class Selector: It selects HTML elements using specific class attributes.
Syntax: .classname
语法:.classname Example: Here is the CSS rule that will be applied to the HTML element with class="scaler". 示例:以下是应用于具有 class="scaler" 的 HTML 元素的 CSS 规则。
Child Selector or Combinator: It selects all HTML elements that are children of the specified element. In a child selector, there are two or more selectors separated by ">".
Syntax: selector1 > selector2
语法:selector1 > selector2 Example: Here is a CSS rule that will be applied to HTML elements () that are children of a element. 示例:以下是应用于某个 元素的子元素的 HTML 元素的 CSS 规则。
div > p {
div > p { background-color: blue; background-color: blue; }
A pseudo-class is basically used to define or specify a special state of an HTML element. This can be used in conjunction with an existing CSS selector to add effects to elements based on their state. For instance, changing the style of an element when a user hovers over it or using different styles for visited and unvisited links. The pseudo-class gives you the ability to do all of this.
selector: pseudo-class{ property: value; property: value; } In CSS, there are many pseudo-classes, but the ones that are most frequently used are as follows: - :visited pseudo-class: Select the links that the user has already visited. 在CSS中,有许多伪类,但最常用的如下:- :visited伪类:选择用户已经访问过的链接。
:hover pseudo-class: A special effect can be added to an element when the mouse pointer is over it.
:active pseudo-class: Select the element that becomes active when the user clicks on it.
:focus pseudo-class: Select an element that is currently focused by the user.
Media queries are used in CSS to create responsive web designs. This means that the way a web page appears varies from one system to another based on the screen or the media type. The media query can be used to apply different styles or change the appearance (and even the behaviour) of a site or an app depending on a user's device type or specific characteristics (like browser viewport width, height, screen resolution, etc.). The following can be checked using media queries: - Dimensions (width and height) of the viewport
In simple terms, Canvas ( tag) is an HTML element that enables you to draw or create graphics on a web page using JavaScript. This is a new tag in HTML5. Canvas allows you to dynamically control graphics, images, and text on your web pages, adding a great deal of interactivity. You can create graphs, combine photos, and create animated elements using the CANVAS element.
In this example, we have a simple *canvas> element that only has two specific attributes: width (set width of the canvas) and height (set height of the canvas), along with the HTML5 core attributes such as id, name, and class.
In JavaScript, a closure is known as a JavaScript closure or JS closure. Closures allow you to access the scope (variables and parameters) of an outer function from an inner function. Every time a JavaScript function is created, a closure is created. JavaScript closures allow you to control which variables are and are not in scope in a given function, as well as which variables are shared among siblings within the same containing scope.
AJAX (Asynchronous JavaScript and XML) refers to a set of technologies used for developing web applications. The purpose of AJAX is to create better, faster, and more interactive web applications using these technologies such as XML, HTML/XHTML, CSS, DOM, JavaScript, XMLHttpRequest etc. Through Ajax, web applications are able to send and receive data asynchronously from the server without hampering the display or behaviour of the existing site. Using AJAX, you can exchange information with a server and update portions of a webpage without having to reload the whole page. The term "AJAX" refers to a technique for creating dynamic, fast web pages.
Typically, it depends on how your site is laid out and how users interact with it. The most efficient way, however, would be to use just a single file called styles.css (or something similar). Combining them into a single document is preferable. Loading one file is easier for a client than loading five. In order to change the style, you simply open the styles.css file, scroll down to find the appropriate section, and modify the CSS. The sheet can be linked in your HTML as follows:
As a Web Developer, here are the top hacks for reducing load time and optimizing your web application's loading times: - Image compression and optimization: Using images on your website will improve the appearance and quality of your pages. However, larger images will also slow down the loading process. Compressing and optimizing images is one of the easiest ways to improve the speed of your site. The smaller your images' file sizes, the less weight they have, which, in turn, helps your pages load faster.
Put JavaScript and CSS in external files: When JavaScript and CSS are embedded in HTML documents, they are downloaded each time the HTML document is loaded. As a result, this does not utilize browser caching, increasing the size of HTML documents. You should always place CSS and JavaScript in external files; this is best practice and makes maintaining your site easier.
Reduce the number of redirects: A website with too many redirects will take a long time to load. HTTP request and response times are prolonged every time a page redirects. If you eliminate unnecessary redirects on your site, your page load time will be significantly reduced.
CSS and JavaScript files should be loaded asynchronously: You have CSS and JavaScript files on your website that can be loaded synchronously or asynchronously. In synchronous loading, each file is loaded one at a time, in the order in which it appears on your web page. Asynchronous loading, on the other hand, allows multiple files to be loaded simultaneously, which can speed up the performance of a website. '
Minify HTML, CSS, and JavaScript: Your pages will load faster if you optimize how your files to load. In a similar vein, you can minify your HTML, CSS, and JavaScript code. You can reduce the size of files by eliminating unnecessary spaces, characters, comments, and other components. As a result, web pages will load faster with cleaner code.
NPM stands for Node Package Manager . It is commonly used as a default package manager for Node.js (JavaScript runtime environment). It is included in every installation of Node.js. This command-line tool installs, updates, and uninstalls Node.js packages and modules required for Node applications or projects. A package contains all files for a module, and modules are basically JavaScript libraries that can be added to a Node project as needed. It contains a number of libraries that are extremely useful to Node.js developers, speeding up the process of developing applications.
Check NPM Version: The following syntax can be used to check the version of NPM that is installed on the system:
检查 NPM 版本:以下语法可用于检查系统上安装的 NPM 版本:
Syntax: npm -v
语法:npm -v
Update NPM Version: NPM updates refer to updating the Node package manager to its latest version. One may always update the installed version if it is not the latest using the syntax given below:
Managing the availability of variables or objects in an application is governed by the concept of scope. In JavaScript, there are two types of scope as follows:
Global Scope: A variable having global scope can be accessed from anywhere in the program. These variables that are declared outside of any function can be accessed from any place in the program.
let scalerProgram = "DataScience" // code here can use scalerProgram // 这里可以访问 scalerProgram function myScaler() { function myScaler() { // code here can also use scalerProgram // 这里的代码也可以使用 scalerProgram } Local Scope : Variables with a local scope can only be accessed within the same function in which they are declared. Whenever a variable is declared inside a function, it becomes local to the function. As soon as a function begins, local variables are created and deleted when the function is executed. 局部作用域:具有局部作用域的变量只能在声明它们的同一个函数内访问。每当在函数内声明变量时,该变量就成为该函数的局部变量。一旦函数开始执行,局部变量就会被创建,并在函数执行完毕后被删除。
Example:
示例:
// code here can NOT use scalerProgram
// 这里的代码不能使用 scalerProgram function myScaler() { function myScaler() { let scalerProgram = "DataScience"; let scalerProgram = "DataScience"; // code here CAN use scalerProgram // 这里的代码可以使用 scalerProgram } // code here can NOT use scalerProgram // 这里的代码不能使用 scalerProgram
Typically, there are three types of web developer jobs based on skills: front-end, back-end, and full-stack development. Front-end web developers design the look of a website (visible to users) and focus on visual elements of the website. A backend developer is responsible for server-side (non-visible to users) application logic and front-end integration. Full Stack Developers work both on the Back End (server-side) and Front End (client-side) of an application.
For a beginner, learning web development from the ground up would take you about four to six months if you study 2-3 hours every day. Some people learn within a couple of months, while others take a year or so.
Web Developers must have a good understanding of HTML, CSS, and JavaScript. Additionally, you should learn about libraries and frameworks such as Bootstrap and jQuery. Having these foundational skills will help you understand how programming languages work.
Anyone can become a web developer ; anyone who is interested in creating websites should learn how to do so. You don't have to be a techie or have a long list of formal qualifications to pursue a career in web development. It only takes motivation and a willingness to learn to climb the career ladder.
For creating websites and web applications, web developers use programming languages (such as JavaScript, and Python). A developer turns the plans and visions of web designers into what you see on your phone, tablet, or computer screen by using code.
It is estimated that web developers with 1-4 years of experience can earn around Rs 3,04,000 per annum. With 5-9 years of experience, you can expect to make around Rs 5,89,000 per year. Over ten years of experience in this field can earn you around Rs 1,000,000 annually. However, the range of the salary depends on a variety of factors such as your experience, employer (company profile), skills, and location.
As people embark on further education and prepare to enter some well-reputed organization, this is likely to be one of the most common questions they encounter.
当人们开始进一步教育并准备进入一些知名组织时,这可能是他们遇到的最常见问题之一。
Sample Answer: "As a fresher, I am interested in starting my career with a company like yours. I am well versed in all the required subjects. Even though I am a newbie, I am a very quick learner, and I am also highly trainable. By having these two skills, I am able to learn new techniques and skills very fast, and I also adjust to new environments more quickly. I have a few fresh ideas that may help your company grow and thrive. Furthermore, I would like to learn from professionals working with your team and refine my skills".
The main difference between web developers and software developers pertains to the types of projects they may work on. The role of a web developer is to develop web-based applications such as websites, e-commerce, and mobile applications. As a software developer, you will focus on developing software for underlying operating systems, networks, or platforms. Software developers can be involved in the service development of web applications, etc.
Make sure you categorize your project into several steps and explain them in a very clear manner in order to win an interview. Here are some steps to explain a project: - Project Introduction
Different web development types include: - Front-end: Front-end developers design the look of a website (visible to users) and focus on visual elements of the website.
不同的Web开发类型包括:- 前端:前端开发人员设计网站的外观(用户可见)并专注于网站的视觉元素。
Back-end: A backend developer is responsible for server-side (non-visible to users) application logic and front-end integration.
Full Stack: Full Stack Developers work both on the Back End (server-side) and Front End (client-side) of an application.
UI (User Interface) developers: UI developers are responsible for designing and developing a website's User Interface. They design the look, feel, and presentation of web applications, as well as ensure their functionality.
评论